Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.6k views
in Technique[技术] by (71.8m points)

dart - How to programmatically select BottomNavigationBar Tab in Flutter instead of built in onTap callback?

I have been working with BottomNavigationBar in the flutter, but I am not able to select a Tab programmatically outside of onTap callback of BottomNavigationBar.

The code with onTap callback, which is working:

    return new BottomNavigationBar(
  items: <BottomNavigationBarItem>[
    _bottomNavigationItem(Icons.account_circle, DrawerTitles.CONTACTS),
    _bottomNavigationItem(Icons.delete, DrawerTitles.DELETED_CONTACTS),
    _bottomNavigationItem(Icons.list, DrawerTitles.LOGS),
  ],
  onTap: (int index) {
    setState(() {
      navigationIndex = index;
      switch (navigationIndex) {
        case 0:
          handleBottomNavigationBarClicks(DrawerTitles.CONTACTS);
          break;
        case 1:
          handleBottomNavigationBarClicks(DrawerTitles.DELETED_CONTACTS);
          break;
        case 2:
          handleBottomNavigationBarClicks(DrawerTitles.LOGS);
          break;
      }
    });
  },
  currentIndex: navigationIndex,
  fixedColor: Colors.blue[400],
  type: BottomNavigationBarType.fixed,
);

But I want to change the tabs outside of onTap callback.

I have tried changing the index used by BottomNavigatioBar outside of onTap callBack, but it didn't work.

Here is what I have tried:

void changeTabs(int tabIndex) {
setState(() {
     navigationIndex = tabIndex;
});}

Here is a gist for the code.

Is there any way available to change Tabs?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You can grab this BottomNavigationBar widget by using a GlobalKey. By this GlobalKey you can handle this widget. Here is an gist for the code

Here you assign a GlobalKey

GlobalKey globalKey = new GlobalKey(debugLabel: 'btm_app_bar');

And put that key in your BottomNavigationBar

new BottomNavigationBar(
    key: globalKey,
    items: [...],
   onTap: (int index) {...},
  ),

Now you can call widget's method and use CurvedNavigationBar instead of BottomNavigationBar if you have to work with CurvedNavigationBar.

 final BottomNavigationBar navigationBar = globalKey.currentWidget;
 navigationBar.onTap(2);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...