Flutter Bottom Navigation Bar Explained

Flutter Bottom Navigation Bar

Just like any other Bar in Flutter, Bottom Navigation Bar takes one important property.

BottomNavigationBar

It takes items property and items property take list of children. So any kind widget that has Bar keyword(like tabbar, tabbarview or sliverappbar), takes list of children.

It takes other few important property like

onTap

currentIndex

We use onTap property to change the index of the selected item and get selected. And then we pass this index to the currentIndex.

 

If you can not change the background color of the bottom navigation bar, see the video

The background color changes, if you have a fourth tab bar in the bottom navigation bar item. Flutter changes the background color to the default one if you add more than three tabs. The fourth tab creates shifting in position if you click on the tab bar item. To solve this you need to 

type:BottomNavigationBarType.fixed

 

If you get error like this 

'package:flutter/src/painting/text_painter.dart': Failed assertion: line 900 pos 12: '!_needsLayout': is not true.

You get this error if you have the below property settings for flutter bottom navigation bar 

   showSelectedLabels: false,
   showUnselectedLabels: false,

To over this issue, you can set another two properties

unselectedFontSize: 0.0,
selectedFontSize: 0.0,

Now the overall bottom navigation bar code should look like this

 @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: pages[currentIndex],
      bottomNavigationBar: BottomNavigationBar(
        /*
        below two lines helps with the error of needs layout
         */
        unselectedFontSize: 0.0,
        selectedFontSize: 0.0,
        type:BottomNavigationBarType.fixed,
        backgroundColor: Colors.white,
        showSelectedLabels: false,
        showUnselectedLabels: false,
        selectedItemColor: Colors.black,
        unselectedItemColor: Colors.grey,
        elevation: 0,
        onTap: onTap,
        currentIndex: currentIndex,
        items: [
           BottomNavigationBarItem(title:Text("Home"),icon: Icon(Icons.apps)),
           BottomNavigationBarItem(title:Text("Bar"),icon: Icon(Icons.bar_chart)),

          BottomNavigationBarItem(title:Text("Search"),icon: Icon(Icons.search)),
          BottomNavigationBarItem(title:Text("Me"),icon: Icon(Icons.person))
      ],

      ),
    );
  }