Dynamic Bottom Navigation Bar from list Flutter

1,000
  1. Create a custom class
    class MyTabItem {

    String title;
    IconData icon;

    MyTabItem(this.name, this.icon);

    }
  1. Create list of tabs:
List<MyTabItem> _items = [
  MyTabItem('Home', Icons.home),
  MyTabItem('Business', Icons.business),
  MyTabItem('School', Icons.school),
];
  1. Create a method to iterate through the _items collection and returns List<BottomNavigationBarItem>
List<BottomNavigationBarItem> getBottomTabs( List<MyTabItem> tabs) {
    return tabs
        .map(
          (item) =>
          BottomNavigationBarItem(
            icon: Icon(item.icon),
            label: item.title,
          ),
    )
        .toList();
  }
  1. Finally, call the method:
bottomNavigationBar: BottomNavigationBar(
          items: getBottomTabs(items),
         ),

Answer was inspired by @Muldec response here: Flutter: Show different icons based on value

Share:
1,000
Soveyyy
Author by

Soveyyy

Updated on December 30, 2022

Comments

  • Soveyyy
    Soveyyy over 1 year

    How to make a bottom navbar which the bottom navbar item get data from list?

    bottom navbar example from flutter documentation

    bottomNavigationBar: BottomNavigationBar(
        items: const <BottomNavigationBarItem>[
          BottomNavigationBarItem(
            icon: Icon(Icons.home),
            label: 'Home',
          ),
          BottomNavigationBarItem(
            icon: Icon(Icons.business),
            label: 'Business',
          ),
          BottomNavigationBarItem(
            icon: Icon(Icons.school),
            label: 'School',
          ),
        ],
        currentIndex: _selectedIndex,
        selectedItemColor: Colors.amber[800],
        onTap: _onItemTapped,
      ),