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

Harsh Sharma picture Harsh Sharma · Jun 21, 2018 · Viewed 14.3k times · Source

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?

Answer

Huy Ho&#224;ng picture Huy Hoàng · Jun 21, 2018

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);