Flutter中BottomNavigationBarItem的title参数报错,如何修正并配置?
问题修正方案
报错原因
Flutter 2.0及以上版本中,BottomNavigationBarItem的title参数已被废弃并移除,取而代之的是label参数,这就是触发No named parameter with the name 'title'错误的直接原因。
基础修正代码
将原代码中的title参数替换为label即可解决报错。如果需要设置文字样式,推荐通过BottomNavigationBar的全局样式属性统一控制,这样能保证选中/未选中状态的样式一致性:
import 'package:flutter/material.dart'; import 'package:font_awesome_flutter/font_awesome_flutter.dart'; class BottomNavBarWidget extends StatefulWidget { @override _BottomNavBarWidgetState createState() => _BottomNavBarWidgetState(); } class _BottomNavBarWidgetState extends State<BottomNavBarWidget> { // 将选中索引变量移到build方法外,避免每次重建页面时重置状态 int _selectedIndex = 0; void _onItemTapped(int index) { setState(() { _selectedIndex = index; // navigateToScreens(index); }); } @override Widget build(BuildContext context) { return BottomNavigationBar( type: BottomNavigationBarType.fixed, items: const <BottomNavigationBarItem>[ BottomNavigationBarItem( icon: Icon(Icons.home), label: 'Home', // 替换原title参数为label ), // 可添加更多底部导航项 BottomNavigationBarItem( icon: Icon(Icons.settings), label: 'Settings', ), ], currentIndex: _selectedIndex, selectedItemColor: const Color(0xFFfd5352), // 设置选中状态的文字样式 selectedLabelStyle: const TextStyle( color: Color(0xFFfd5352), fontWeight: FontWeight.bold, ), // 设置未选中状态的文字样式 unselectedLabelStyle: const TextStyle( color: Color(0xFF2c2b2b), ), onTap: _onItemTapped, ); } }
自定义单个导航项的文字样式(特殊场景)
如果需要给某个特定的BottomNavigationBarItem设置独立于全局的样式,可以结合activeIcon和icon属性,将图标与文字封装为自定义Widget,手动处理选中/未选中状态的UI变化:
BottomNavigationBarItem( icon: Column( mainAxisAlignment: MainAxisAlignment.center, children: const [ Icon(Icons.home), SizedBox(height: 4), Text( 'Home', style: TextStyle(color: Color(0xFF2c2b2b)), ), ], ), activeIcon: Column( mainAxisAlignment: MainAxisAlignment.center, children: const [ Icon(Icons.home, color: Color(0xFFfd5352)), SizedBox(height: 4), Text( 'Home', style: TextStyle(color: Color(0xFFfd5352), fontWeight: FontWeight.bold), ), ], ), label: '', // 留空避免重复显示文字 ),
内容的提问来源于stack exchange,提问作者Student
相关产品推荐
相关产品推荐

