在flutter中导航到其他页面时如何解决底部导航栏丢失的问题

时间:2020-03-23 09:57:03

标签: flutter

我正在使用Flutter。我有3个标签的底部导航。当我使用Navigator.push()选项卡2,但底部导航丢失。如何解决这个问题?

这是我的 tabController.dart

class _TabsControllerState extends State<TabsController> {
final List<Widget> pages = [
    HomePage(
      key: PageStorageKey('page1'),
    ),
    CartPage(
      key: PageStorageKey('page2'),
    ),
    ProfilePage(
      key: PageStorageKey('page3'),
    ),
  ];
      final PageStorageBucket bucket = PageStorageBucket();

      var _selectedIndex = 0;

      Widget _bottomNavigationBar(var selectedIndex) => BottomNavigationBar(
        onTap: (var index) => setState(() => _selectedIndex = index),
        currentIndex: selectedIndex,
        type: BottomNavigationBarType.fixed,
        items: const <BottomNavigationBarItem>[
          BottomNavigationBarItem(
            icon: Icon(Icons.home), title: Text('Home')),
          BottomNavigationBarItem(
            icon: Icon(Icons.lightbulb_outline), title: Text('Cart')),
          BottomNavigationBarItem(
            icon: Icon(Icons.account_circle), title: Text('Profile')),
          ],
        );

     @override
      Widget build(BuildContext context) {
        return WillPopScope(
            onWillPop: ()async{
              if(_selectedIndex == 0)
              return true;
              else setState(() {
                _selectedIndex = 0;
              });
              return false;
            },
            child: Scaffold(
              bottomNavigationBar: _bottomNavigationBar(_selectedIndex),
              body: PageStorage(
                child: pages[_selectedIndex],
                bucket: bucket,
              ),
            ));
      }
    }

CartPage中,我有详细信息页面。在“详细信息”页面中,当我按按钮时,我想转到HomePage。我该怎么办?

这是我的代码:

new FlatButton(
              child: new Text("OK"),
              onPressed: () {
                Navigator.of(context).push(MaterialPageRoute(builder: (context) => HomePage()));
              },
            ),

1 个答案:

答案 0 :(得分:0)

如果您在BottomNavigationBaron the "Sample in App" Tab of the example上查看Flutter API文档中的示例,您将看到它显示了BottomNavigationBar控制的内容是上面在同一类中声明。您应该做同样的事情。

请记住,您可以简单地将小部件保存在其他文件中,将其导入并实例化以用作每个选项卡。

已更新

以下是有关如何在您的代码中实现它的说明:

在您的主类中声明一个方法,以更改可使用的Tab索引并将其传递给其他类:

void setTabIndex(index){
  setState((){
    _selectedIndex = index;
  });
}

在CartPage类中,在构造函数上为Function类型声明一个变量:

Function setTabIndex;

您的按钮想要这样:

FlatButton(
  child: new Text("OK"),
  onPressed: () {
    setTabIndex(0);
    // 0 is the position of your HomePage in your pages List
  },
),