Flutter使用CurvedNavigationBar默认选中项与预期不符如何解决
问题解决方法
问题原因
CurvedNavigationBar组件默认使用内置的index参数控制选中项下标,默认值为0。你的代码中仅修改了自定义的selectedPage变量,未将该变量绑定到CurvedNavigationBar的index属性,导致组件选中状态和页面展示逻辑不同步。
修复步骤
- 给CurvedNavigationBar组件添加
index参数,绑定你的selectedPage变量 - (可选规范优化)调整initState执行顺序,Flutter开发规范要求先调用
super.initState()再执行自定义逻辑
修复后的核心代码
修正initState执行顺序
@override void initState() { // 先调用父类初始化方法 super.initState(); _pageOption = [ InsightPage(), TradesPage(), DashboardPage(member), PerformencePage(), SettingsPage(), ]; selectedPage = 2; }
修正CurvedNavigationBar配置
bottomNavigationBar: CurvedNavigationBar( height: 50, key: _bottomNavigationKey, // 新增这行,绑定选中下标变量 index: selectedPage, items: [ Icon(Icons.insights, color: Color(0xffffae88), size: 30), Icon(Icons.list, color: Color(0xffffae88), size: 30), Icon(Icons.dashboard, color: Color(0xffffae88), size: 30), Icon(Icons.speed, color: Color(0xffffae88), size: 30), Icon(Icons.settings, color: Color(0xffffae88), size: 30), ], color: secondColor, buttonBackgroundColor: secondColor, backgroundColor: backgroundColor, animationCurve: Curves.easeInOut, animationDuration: Duration(milliseconds: 600), onTap: (index) { setState(() { selectedPage = index; }); }, ),
效果验证
修改完成后重新运行,页面首次加载时CurvedNavigationBar会默认选中第三个图标,和当前展示的Dashboard页保持同步,点击切换其他图标时状态也会正常联动。
内容的提问来源于stack exchange,提问作者Wizeep
相关产品推荐
相关产品推荐

