Flutter 底部导航栏颜色

14
我正在尝试更改BottomNavigation图标的选定颜色,但似乎只能更改文本颜色。请帮助:
当前,当选中时,文本颜色会变为黄色,但图标保持白色,我希望它也是黄色的,我已经尝试将非活动图标的图标颜色设置为灰色,就像标题一样,但没有效果。 enter image description here 以下是我的代码:
new Theme(
        data: Theme.of(context).copyWith(
          canvasColor: Colors.black,
          splashColor: Colors.yellowAccent,
            unselectedWidgetColor: Colors.green,
          primaryColor: Colors.red,
          textTheme: Theme.of(context).textTheme.copyWith(caption: new TextStyle(color: Colors.grey))
        ),
        child: new BottomNavigationBar(
          items: <BottomNavigationBarItem>[
            new BottomNavigationBarItem(
                icon: const Icon(Icons.add_shopping_cart, color: Colors.white,),
                title: new Text("Services"),
            ),
            new BottomNavigationBarItem(
                icon: new Theme(
                  data: new ThemeData(

                  ),
                    child: const Icon(Icons.calendar_today, color: Colors.white,)),
                title: new Text("Appointment")
            ),
            new BottomNavigationBarItem(
                icon: const Icon(Icons.face, color: Colors.white,),
                title: new Text("Profile")
            )
          ],
          currentIndex: index,
          onTap: (int i){setState((){index = i;});},
          fixedColor: Colors.yellowAccent,
          type: BottomNavigationBarType.fixed,
        ),
      )
3个回答

17
不要在BottomNavigationBarItem中声明图标的颜色,应该在BottomNavigationBar中声明unselectedItemColorselectedItemColor属性。
   bottomNavigationBar:
    BottomNavigationBar(
      unselectedItemColor: Colors.green,
      selectedItemColor: Colors.yellow,
      items: [
        BottomNavigationBarItem(
          icon: Icon(Icons.add_shopping_cart),
        ),
      ],
    );

这样做,你的代码就能正常工作了。


15
你已经明确地为每个图标设置了color: Colors.white,所以它们会一直保持白色,除非你另外设置。
你有几个选择:
1. 将你的BottomNavigationBar的类型设置为type: BottomNavigationBarType.fixed,并设置fixedColor: Colors.orange或者你想要的任何颜色。请注意,你必须删除color: Colors.white,否则它们仍然会是白色。
2. 你可以测试正确的索引是否被设置,然后直接决定将图标设置为哪种颜色,例如对于第一项,color = index == 0 ? selectedColor : unselectedColor,对于第二项,index==1,对于第三项,item==2
3. 一个小小的变化是在整个BottomNavigationBar周围设置一个颜色为unselectedColor的IconTheme,然后只为选中的项设置color = index == 0 ? selectedColor : null
我建议阅读BottomNavigationBar文档,特别是关于固定与移动部分,因为它描述了你遇到的确切问题的答案。
请注意,BottomNavigatorBar不再推荐用于新代码,因为它已被更灵活的NavigationBar取代。

1
链接已失效。这是更新后的链接:https://api.flutter.dev/flutter/material/BottomNavigationBar-class.html另外,值得一提的是,您可能希望迁移到NavigationBar。它可以接受任何小部件,而不仅仅是BottomNavigationBarItem,这样您就可以更好地控制项目。 - undefined

2

这是如何设置图标颜色的方法:

bottomNavigationBar: BottomNavigationBar(
              selectedIconTheme: IconThemeData(color: Colors.yellow),
              unselectedIconTheme:  IconThemeData(color: Colors.white),

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接