如果使用底部导航栏,如何从其他选项卡更改活动选项卡?

时间:2019-02-24 20:09:09

标签: flutter

我需要添加“转到其他标签”之类的按钮,并能够将用户从该标签导航到其他任何标签。如果我使用bottomNavigationBar方法,是否可以?

2 个答案:

答案 0 :(得分:0)

BottomNavigationBar具有一个名为currentIndex的属性,您可以分配一个数字,然后使用setState(){}方法单击该数字即可更改该数字。

答案 1 :(得分:0)

好的。它只是保存所选索引的int。我为您提供了一个小例子。

example

class MyApp extends StatefulWidget {
  @override
  _MyAppState createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
  int _selectedIndex = 0;

  void _goToTab(int index) => setState(() => _selectedIndex = index);

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(),
      bottomNavigationBar: BottomNavigationBar(
        currentIndex: _selectedIndex,
        onTap: _goToTab,
        items: <BottomNavigationBarItem>[
          BottomNavigationBarItem(icon: Icon(Icons.mail), title: Text('Item 1')),
          BottomNavigationBarItem(icon: Icon(Icons.mood), title: Text('Item 2')),
          BottomNavigationBarItem(icon: Icon(Icons.message), title: Text('Item 3')),
        ],
      ),
      body: List.unmodifiable([
        Center(child: RaisedButton(onPressed: () => _goToTab(1), child: Text('Go to tab 2'))),
        Center(child: RaisedButton(onPressed: () => _goToTab(2), child: Text('Go to tab 2'))),
        Center(child: RaisedButton(onPressed: () => _goToTab(0), child: Text('Go to to back to tab 1'))),
      ])[_selectedIndex],
    );
  }
}
相关问题