Flutter 1.22后如何为BottomNavigationBarItem的label添加TextStyle
嘿,这个问题我升级Flutter 1.22的时候也踩过坑!确实,BottomNavigationBarItem的title参数被弃用后,新的label只能传字符串,没法直接塞Text组件来定制样式了。不过官方其实提供了更简洁统一的解决方案,不用慌,看下面两种常用方法:
方法一:直接在BottomNavigationBar上统一设置样式
这是最直接的方式,你可以给整个底部导航栏设置选中和未选中状态下的文字样式,代码修改如下:
BottomNavigationBar( items: const [ BottomNavigationBarItem(icon: Icon(Icons.notifications), label: 'tickets'), BottomNavigationBarItem(icon: Icon(CustomIcons.calendar), label: 'calendar'), BottomNavigationBarItem(icon: Icon(CustomIcons.home), label: 'home'), BottomNavigationBarItem(icon: Icon(CustomIcons.podcasts), label: 'microphone'), BottomNavigationBarItem(icon: Icon(CustomIcons.search), label: 'search') ], // 选中状态下的文字样式 selectedLabelStyle: const TextStyle( fontSize: 14, fontWeight: FontWeight.w600, color: Colors.deepOrange, ), // 未选中状态下的文字样式 unselectedLabelStyle: const TextStyle( fontSize: 12, color: Colors.grey.shade600, ), // 可选:统一设置图标和文字的选中/未选中颜色(如果样式里没指定color的话) selectedItemColor: Colors.deepOrange, unselectedItemColor: Colors.grey.shade600, )
方法二:全局主题配置(适合整个App风格统一的场景)
如果你的App里所有底部导航栏都想用同一种样式,可以在ThemeData里配置,这样所有页面的BottomNavigationBar都会自动应用这个样式:
MaterialApp( theme: ThemeData( bottomNavigationBarTheme: const BottomNavigationBarThemeData( selectedLabelStyle: TextStyle( fontSize: 14, fontWeight: FontWeight.w600, ), unselectedLabelStyle: TextStyle( fontSize: 12, ), selectedItemColor: Colors.deepOrange, unselectedItemColor: Colors.grey.shade600, ), ), home: YourHomePage(), )
补充说明
官方这次改动主要是为了让底部导航栏的样式更统一,避免每个BottomNavigationBarItem单独设置样式导致的视觉不一致。如果真的需要给某几个item单独设置特殊样式,可能需要自定义底部导航栏组件,但大部分场景下,上面两种方法完全够用啦。
内容的提问来源于stack exchange,提问作者Arnav
相关产品推荐
相关产品推荐

