'Dynamic Bottom Navigation Bar from list Flutter
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,
),
Solution 1:[1]
- Create a custom class
class MyTabItem {
String title;
IconData icon;
MyTabItem(this.name, this.icon);
}
- Create list of tabs:
List<MyTabItem> _items = [
MyTabItem('Home', Icons.home),
MyTabItem('Business', Icons.business),
MyTabItem('School', Icons.school),
];
- Create a method to iterate through the
_itemscollection and returnsList<BottomNavigationBarItem>
List<BottomNavigationBarItem> getBottomTabs( List<MyTabItem> tabs) {
return tabs
.map(
(item) =>
BottomNavigationBarItem(
icon: Icon(item.icon),
label: item.title,
),
)
.toList();
}
- Finally, call the method:
bottomNavigationBar: BottomNavigationBar(
items: getBottomTabs(items),
),
Answer was inspired by @Muldec response here: Flutter: Show different icons based on value
Solution 2:[2]
try this:
List<String> items = ['Home', 'Business', 'School'];
bottomNavigationBar: BottomNavigationBar(
items: items.map((item) {
Widget itemIcon = Icon(Icons.home);
if(item == 'Home')
{
itemIcon = Icon(Icons.home),
}else if(item == 'Business')
{
itemIcon = Icon(Icons.business),
}else if(item == 'School')
{
itemIcon = Icon(Icons.school),
}
BottomNavigationBarItem(
icon: itemIcon ,
label: item,
),
}).toList(),
currentIndex: _selectedIndex,
selectedItemColor: Colors.amber[800],
onTap: _onItemTapped,
),
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | user18234053 |
| Solution 2 | Jim |
