1

如何制作底部导航栏,底部导航栏项目从列表中获取数据?

颤振文档中的底部导航栏示例

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,
  ),
4

2 回答 2

0
  1. 创建自定义类
    class MyTabItem {

    String title;
    IconData icon;

    MyTabItem(this.name, this.icon);

    }
  1. 创建选项卡列表:
List<MyTabItem> _items = [
  MyTabItem('Home', Icons.home),
  MyTabItem('Business', Icons.business),
  MyTabItem('School', Icons.school),
];
  1. 创建一个方法来遍历_items集合并返回List<BottomNavigationBarItem>
List<BottomNavigationBarItem> getBottomTabs( List<MyTabItem> tabs) {
    return tabs
        .map(
          (item) =>
          BottomNavigationBarItem(
            icon: Icon(item.icon),
            label: item.title,
          ),
    )
        .toList();
  }
  1. 最后调用方法:
bottomNavigationBar: BottomNavigationBar(
          items: getBottomTabs(items),
         ),

答案受到@Muldec 回复的启发:Flutter: Show different icons based on value

于 2022-02-17T13:21:41.867 回答
0

尝试这个:

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,
  ),
于 2021-06-18T07:34:55.943 回答