You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.06 20:15:01