底部导航栏和提供者?

时间:2021-03-30 20:35:58

标签: flutter flutter-provider flutter-bottomnavigation

我使用底部导航栏并在底部添加了 3 个按钮。我正在用 setate 交换页面。这些按钮工作正常。但是,如果我在使用这些按钮调用的页面内调用另一个页面,BottomNavigationBar 就会消失。我已经研究过它并发现了这个 click me。使用 Provider 调用页面是否合乎逻辑?我觉得它把每一页都保存在内存中,是不是消耗了太多内存?

 import 'package:flutter/material.dart';

class HomePage extends StatefulWidget {
  @override
  _HomePageState createState() => _HomePageState();
}

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

  final _pageOptions = [
    HomeScreen(),
    InboxScreen(),
    SignInScreen()
  ];

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        backgroundColor: Colors.white,
        body: _pageOptions[selectedPage],
        bottomNavigationBar: BottomNavigationBar(
          items: [
            BottomNavigationBarItem(icon: Icon(Icons.home, size: 30), title: Text('Home')),
            BottomNavigationBarItem(icon: Icon(Icons.mail, size: 30), title: Text('Inbox')),
            BottomNavigationBarItem(icon: Icon(Icons.account_circle, size: 30), title: Text('Account')),
          ],
          selectedItemColor: Colors.green,
          elevation: 5.0,
          unselectedItemColor: Colors.green[900],
          currentIndex: selectedPage,
          backgroundColor: Colors.white,
          onTap: (index){
            setState(() {
              selectedPage = index;
            });
          },
        )
    );
  }
}

这是我的主页。如果我点击文本,BottomNavigationBar 就会消失

class _HomePage extends State<HomePage> {
  @override
  Widget build(BuildContext context) {
    // TODO: implement build
    return Scaffold(appBar: AppBar(title: Text('Page2')),body:GestureDetector(
        onTap: () {
    
            Navigator.of(context).push(MaterialPageRoute(builder: (context) => NewScreen()));

        },
        child:Text('clik')));
  }
}

我想要这个 I want to this 但是我的代码运行这个 not this

1 个答案:

答案 0 :(得分:0)

您发布的代码看起来非常好!
您的问题一定在别处,可能在其中一个小部件中

final _pageOptions = [
  HomeScreen(),
  InboxScreen(),
  SignInScreen()
];

您的问题可能有很多根本原因,您可以首先确定是哪个 Widget 使底部导航栏消失。
一旦发现,请确保您没有使用方法 Navigator.of(context).push,这可能是您的底部导航栏消失的原因之一。

如果您仍然被卡住,请随时使用使栏消失的 Widget 的源代码更新您的问题,我会更新我的答案

编辑
正如我之前提到的,每当您调用 Navigator.push(context, UserProfilePage); 方法时,您都会用一个新的小部件替换之前的小部件。
由于您之前的 Widget 持有您的 bottomNavigationBar,这就是它消失的原因。

您在这里寻找的是,如何拥有一个持久的导航栏。
这里有两个有用的链接,可以帮助您和其他有此需求的人,a Video tutorial to understand how to implement itwell written article to fully understand how it works