Флаттер - навигация с помощью BottomNavigationBar - PullRequest
0 голосов
/ 11 марта 2020

В моем приложении «Домашняя страница» с BottomNavigationBar уже установлена ​​и работает с 4 различными страницами. После того, как я захожу на экран «Perfil» и перехожу на другие дочерние экраны (PaymentForm) и пытаюсь go вернуться на страницу «Perfil», BottomNavigationBar там нет. Как мне вернуться на «Домашнюю страницу» с индексом, соответствующим этому экрану «Perfil»? Коды ниже.

Домашняя страница () с BottomNavigationBar:

class HomePage extends StatefulWidget {

  @override
  _HomePageState createState() => _HomePageState();
}

class _HomePageState extends State<HomePage> {
  int _currentIndex = 0;

  final tabs = [
    Center(child: MainPage()),
    Center(child: Text('Busca')),
    Center(child: Text('Pedidos')),
    Center(child: Perfil()),
  ];

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      debugShowCheckedModeBanner: false,
      home: Scaffold(
        body: tabs[_currentIndex],
        bottomNavigationBar: BottomNavigationBar(
          currentIndex: _currentIndex,
          type: BottomNavigationBarType.fixed,
          items: [
            BottomNavigationBarItem(
              icon: Image.asset(
                'assets/images/home_icone.png',
                width: 40,
                height: 40,
              ),
              title: Text(
                'Inicio',
                style: TextStyle(color: Color(0xff203760)),
              ),
            ),
            BottomNavigationBarItem(
              icon: Image.asset(
                'assets/images/busca_icone.png',
                width: 40,
                height: 40,
              ),
              title: Text(
                'Busca',
                style: TextStyle(color: Color(0xff203760)),
              ),
            ),
            BottomNavigationBarItem(
              icon: Image.asset(
                'assets/images/pedidos_icone.png',
                width: 40,
                height: 40,
              ),
              title: Text(
                'Pedidos',
                style: TextStyle(color: Color(0xff203760)),
              ),
            ),
            BottomNavigationBarItem(
              icon: Image.asset(
                'assets/images/perfil_icone.png',
                width: 40,
                height: 40,
              ),
              title: Text(
                'Perfil',
                style: TextStyle(color: Color(0xff203760)),
              ),
            ),
          ],
          onTap: (index) {
            setState(() {
              _currentIndex = index;
            });
          },
        ),
      ),
    );
  }
}

Perfil ():

class Perfil extends StatefulWidget {

  @override
  _PerfilState createState() => _PerfilState();
}

class _PerfilState extends State<Perfil>{

  final AuthService _auth = AuthService();

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      debugShowCheckedModeBanner: false,
      home: Scaffold(
        body: SingleChildScrollView(
          child: Column(
            children: <Widget>[
              Container(
                decoration: BoxDecoration(
                  border: Border(
                    bottom: BorderSide(
                      color: Colors.blueGrey,
                      width: 1.0,
                    ),
                  ),
                ),
                height: 120,
                width: double.maxFinite,
                margin: EdgeInsets.fromLTRB(0, 20, 0, 0),
                child: Row(
                  mainAxisAlignment: MainAxisAlignment.spaceAround,
                  children: <Widget>[
                    Image.asset(
                      'assets/images/perfil_foto.png',
                      height: 60,
                      width: 60,
                    ),
                    Text(
                      '$nameUser',
                      style: TextStyle(color: Color(0xff203760), fontSize: 28.0),
                      textAlign: TextAlign.center,
                    ),
                    Image.asset(
                      'assets/images/right_arrow.png',
                      height: 40,
                      width: 40,
                    )
                  ],
                ),
              ),
              Padding(
                padding: const EdgeInsets.all(5),
                child: Column(
                  children: <Widget>[
                    ListView(
                      shrinkWrap: true,
                      children: <Widget>[
                        ListTile(
                          leading: Icon(
                            Icons.notifications_none,
                            size: 40.0,
                            color: Color(0xff203760),
                          ),
                          title: Text(
                            "Notificações",
                            style: TextStyle(color: Color(0xff203760), fontSize: 20.0),
                          ),
                          subtitle: Text(
                            "Central de notificações",
                            style: TextStyle(color: Color(0xff203760), fontSize: 16.0),
                          ),
                          onTap: () {},
                        ),
                        ListTile(
                          leading: Icon(
                            Icons.favorite_border,
                            size: 40.0,
                            color: Color(0xff203760),
                          ),
                          title: Text(
                            "Favoritos",
                            style: TextStyle(color: Color(0xff203760), fontSize: 20.0),
                          ),
                          subtitle: Text(
                            "Central de notificações",
                            style: TextStyle(color: Color(0xff203760), fontSize: 16.0),
                          ),
                          onTap: () {},
                        ),
                        ListTile(
                          leading: Icon(
                            Icons.payment,
                            size: 40.0,
                            color: Color(0xff203760),
                          ),
                          title: Text(
                            "Formas de Pagamento",
                            style: TextStyle(color: Color(0xff203760), fontSize: 20.0),
                          ),
                          subtitle: Text(
                            "Central de notificações",
                            style: TextStyle(color: Color(0xff203760), fontSize: 16.0),
                          ),
                          onTap: () {
                            Navigator.of(context).push(MaterialPageRoute(builder: (context) => PaymentForm()));
                          },
                        ),
                        ListTile(
                          leading: Icon(
                            Icons.location_on,
                            size: 40.0,
                            color: Color(0xff203760),
                          ),
                          title: Text(
                            "Endereços",
                            style: TextStyle(color: Color(0xff203760), fontSize: 20.0),
                          ),
                          subtitle: Text(
                            "Central de notificações",
                            style: TextStyle(color: Color(0xff203760), fontSize: 16.0),
                          ),
                          onTap: () {},
                        ),
                        ListTile(
                          leading: Image.asset(
                            'assets/images/logout.png',
                            width: 40,
                            height: 40,
                          ),
                          title: Text(
                            "Sair",
                            style: TextStyle(color: Color(0xff203760), fontSize: 20.0),
                          ),
                          subtitle: Text(
                            "Finalizar sessão",
                            style: TextStyle(color: Color(0xff203760), fontSize: 16.0),
                          ),
                          onTap: () async {
                            await _auth.signOut();
                          },
                        ),
                      ],
                    ),
                  ],
                ),
              )
            ],
          ),
        ),
      ),
    );
  }
}

PaymentForm () (дочерняя страница из Perfil):

class PaymentForm extends StatefulWidget {
  @override
  _PaymentFormState createState() => _PaymentFormState();
}

class _PaymentFormState extends State<PaymentForm> {

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      debugShowCheckedModeBanner: false,
      home: Scaffold(
        body: Column(
          children: <Widget>[
            Container(
              height: 120,
              width: double.maxFinite,
              margin: EdgeInsets.all(0),
              decoration: BoxDecoration(
                border: Border(
                  bottom: BorderSide(
                    color: Colors.blueGrey,
                    width: 0.5,
                  ),
                ),
              ),
              child: Padding(
                padding: const EdgeInsets.fromLTRB(0, 25, 0, 0),
                child: Row(
                  mainAxisAlignment: MainAxisAlignment.start,
                  crossAxisAlignment: CrossAxisAlignment.center,
                  children: <Widget>[
                    Container(
                      padding: const EdgeInsets.fromLTRB(15, 15, 10, 15),
                      child: ClipOval(
                        child: Container(
                          width: 35,
                          height: 35,
                          decoration: BoxDecoration(
                            image: DecorationImage(
                              image: AssetImage('assets/images/left_arrow.png'),
                            ),
                          ),
                          child: FlatButton(
                            padding: EdgeInsets.all(0.0),
                            onPressed: () {
                              print('teste');
                              Navigator.push(
                                context,
                                MaterialPageRoute(
                                    builder: (context) => HomePage()),
                              );
                            },
                            child: null,
                          ),
                        ),
                      ),
                    ),
                    Text(
                      " Formas de pagamento",
                      style:
                          TextStyle(color: Color(0xff203760), fontSize: 28.0),
                      textAlign: TextAlign.center,
                    ),
                  ],
                ),
              ),
            ),
            Padding(
              padding: const EdgeInsets.all(0),
              child: Column(
                children: <Widget>[
                  ListView(
                    shrinkWrap: true,
                    children: ListTile.divideTiles(
                      context: context,
                      color: Color(0xff203760),
                      tiles: [
                        ListTile(
                          title: Text(
                            "Cartão de crédito",
                            style: TextStyle(
                                color: Color(0xff203760), fontSize: 24.0),
                          ),
                          subtitle: Text(
                            "Master ****** 3284",
                            style: TextStyle(
                                color: Color(0xff203760), fontSize: 12.0),
                          ),
                          trailing: Image.asset(
                            'assets/images/menu_dots.png',
                            width: 10,
                          ),
                          onTap: () {
                            Navigator.of(context).push(MaterialPageRoute(
                                builder: (context) => CartManager()));
                          },
                        ),
                      ],
                    ).toList(),
                  ),
                  Row(
                    mainAxisAlignment: MainAxisAlignment.spaceBetween,
                    children: <Widget>[
                      Container(
                        padding: const EdgeInsets.all(15),
                        child: Column(
                          crossAxisAlignment: CrossAxisAlignment.start,
                          children: <Widget>[
                            Text(
                              "Cartão de crédito",
                              style: TextStyle(
                                color: Color(0xff203760),
                                fontSize: 28.0,
                              ),
                            ),
                          ],
                        ),
                      ),
                      Container(
                        padding: const EdgeInsets.all(15),
                        child: ClipOval(
                          child: Container(
                            width: 40,
                            height: 40,
                            decoration: BoxDecoration(
                              image: DecorationImage(
                                image:
                                    AssetImage('assets/images/add_button.png'),
                              ),
                            ),
                            child: FlatButton(
                              padding: EdgeInsets.all(0.0),
                              onPressed: () {
                                print('teste');
                                Navigator.push(
                                  context,
                                  MaterialPageRoute(
                                      builder: (context) => CartAdd()),
                                );
                              },
                              child: null,
                            ),
                          ),
                        ),
                      ),
                    ],
                  ),
                ],
              ),
            )
          ],
        ),
      ),
    );
  }
}

Спасибо за помощь !!!

1 Ответ

0 голосов
/ 11 марта 2020

Ваша проблема в том, что вы используете виджет MaterialApp в каждом классе. Вам не нужно делать это. Только ваш HomePage должен иметь его. На других классах вам нужен только контент, который вы хотите показать. Взяв код, удалив виджеты MaterialApp и упростив его без частей, которыми вы не поделились, он заработает:

class HomePage extends StatefulWidget {

  @override
  _HomePageState createState() => _HomePageState();
}

class _HomePageState extends State<HomePage> {
  int _currentIndex = 0;

  final tabs = [
    Center(child: Text('Main')),
    Center(child: Text('Busca')),
    Center(child: Text('Pedidos')),
    Center(child: Text('Perfil')),
  ];

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      debugShowCheckedModeBanner: false,
      home: Scaffold(
        body: tabs[_currentIndex],
        bottomNavigationBar: BottomNavigationBar(
          currentIndex: _currentIndex,
          type: BottomNavigationBarType.fixed,
          items: [
            BottomNavigationBarItem(
              icon: Icon(Icons.home),
              title: Text(
                'Inicio',
                style: TextStyle(color: Color(0xff203760)),
              ),
            ),
            BottomNavigationBarItem(
              icon: Icon(Icons.home),
              title: Text(
                'Busca',
                style: TextStyle(color: Color(0xff203760)),
              ),
            ),
            BottomNavigationBarItem(
              icon: Icon(Icons.home),
              title: Text(
                'Pedidos',
                style: TextStyle(color: Color(0xff203760)),
              ),
            ),
            BottomNavigationBarItem(
              icon: Icon(Icons.home),
              title: Text(
                'Perfil',
                style: TextStyle(color: Color(0xff203760)),
              ),
            ),
          ],
          onTap: (index) {
            setState(() {
              _currentIndex = index;
            });
          },
        ),
      ),
    );
  }
}
...