列表中的动态底部导航栏Flutter

ggazkfy8  于 2023-02-13  发布在  Flutter
关注(0)|答案(3)|浏览(109)

如何制作一个底部导航栏,其中底部导航栏项目从列表中获取数据?
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,
  ),
bf1o4zei

bf1o4zei1#

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

zynd9foi

zynd9foi2#

试试这个:

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

t1qtbnec3#

不允许评论吉姆的消息。我用他的代码(工作正常),但需要更正这里,我认为:

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

    return BottomNavigationBarItem(     // add return
      icon: itemIcon ,
      label: item,
    );                                  // replace , with ;
  }).toList(),
currentIndex: _selectedIndex,
selectedItemColor: Colors.amber[800],
onTap: _onItemTapped,

),

相关问题