Flutter BottomNavigationBar图标选中颜色修改求助
我来帮你搞定这个BottomNavigationBar的样式问题!你遇到的情况是因为Theme配置里漏掉了控制图标颜色的关键属性,下面给你两种可行的解决方案:
方案一:通过Theme统一全局配置
你需要在Theme的copyWith方法里补充selectedIconTheme和unselectedIconTheme属性,这样就能同时控制图标和文字的选中/未选中颜色:
Theme( data: Theme.of(context).copyWith( canvasColor: Colors.black, splashColor: Colors.yellowAccent, // 配置选中状态的图标颜色 selectedIconTheme: IconThemeData(color: Colors.yellow), // 配置选中状态的文字颜色 textTheme: Theme.of(context).textTheme.copyWith( caption: TextStyle(color: Colors.yellow), ), // 配置未选中状态的图标颜色 unselectedIconTheme: IconThemeData(color: Colors.grey), // 配置未选中状态的文字颜色 unselectedTextTheme: Theme.of(context).unselectedTextTheme.copyWith( caption: TextStyle(color: Colors.grey), ), ), child: BottomNavigationBar( items: [ BottomNavigationBarItem( icon: Icon(Icons.home), label: '首页', ), BottomNavigationBarItem( icon: Icon(Icons.settings), label: '设置', ), ], currentIndex: _selectedIndex, onTap: _onItemTapped, ), )
方案二:直接在BottomNavigationBar组件中单独设置
如果你不想通过Theme做全局配置,也可以直接在BottomNavigationBar组件里设置selectedItemColor和unselectedItemColor,这两个属性会同时作用于图标和文字,更直观:
BottomNavigationBar( backgroundColor: Colors.black, selectedItemColor: Colors.yellow, // 选中时图标+文字统一黄色 unselectedItemColor: Colors.grey, // 未选中时图标+文字统一灰色 splashColor: Colors.yellowAccent, items: [ BottomNavigationBarItem( icon: Icon(Icons.home), label: '首页', ), BottomNavigationBarItem( icon: Icon(Icons.settings), label: '设置', ), ], currentIndex: _selectedIndex, onTap: _onItemTapped, )
为什么你的代码没生效?
你之前的Theme配置只关注了文字相关的属性,但BottomNavigationBar的图标颜色默认是继承Theme的iconTheme,选中状态下会优先使用selectedIconTheme,所以必须显式设置这两个图标主题属性,才能让图标颜色跟着文字一起变化。
试试上面的方案,应该就能实现你想要的效果啦!
内容的提问来源于stack exchange,提问作者spongyboss
相关产品推荐
相关产品推荐

