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

Flutter中BottomNavigationBarItem的label使用变量报错的解决办法

解决BottomNavigationBarItem label无法使用变量的问题

问题根源是你给items列表加了const关键字——const修饰的集合要求内部所有元素及参数必须是编译时常量,而myVariable是运行时定义的普通变量,不符合常量要求,所以哪怕用toString()也没用。

有两种解决办法:

方法一:移除const关键字

直接去掉items前面的const,这样列表就允许使用运行时变量了,直接赋值label: myVariable即可。

修改后的核心代码片段:

items: <BottomNavigationBarItem>[ // 去掉const
  BottomNavigationBarItem(
    icon: Icon(Icons.build_outlined, size: 22),
    label: myVariable, // 直接用变量
    activeIcon: Icon(Icons.build),
  ),
  // ...其他item
],

完整修改后的代码:

Widget build(BuildContext context) {
  String myVariable = "Item1";
  return CupertinoTabScaffold(
    tabBar: CupertinoTabBar(
      backgroundColor: Color.fromARGB(255, 0, 0, 0),
      activeColor: Color.fromARGB(255, 255, 255, 255),
      inactiveColor: Color.fromARGB(255, 160, 160, 160),
      items: <BottomNavigationBarItem>[ // 移除const
        BottomNavigationBarItem(
          icon: Icon(Icons.build_outlined, size: 22),
          label: myVariable,
          activeIcon: Icon(Icons.build),
        ),
        BottomNavigationBarItem(
          icon: Icon(Icons.school_outlined, size: 22),
          label: "Item2",
          activeIcon: Icon(Icons.school),
        ),
      ],
    ),
    tabBuilder: (context, index) {
      switch (index) {
        case 0:
          return CupertinoTabView(builder: (context) {
            return CupertinoPageScaffold(
              child: list_maquina_1(),
            );
          });
        case 1:
          return CupertinoTabView(builder: (context) {
            return CupertinoPageScaffold(
              child: courses_page(),
            );
          });
        default:
          return CupertinoTabView(builder: (context) {
            return CupertinoPageScaffold(
              child: list_maquina_1(),
            );
          });
      }
    },
  );
}

方法二:将变量改为编译时常量(仅适用于固定值场景)

如果你的myVariable值是固定不变的,可以把它声明为const变量,这样就能在const列表里使用:

const String myVariable = "Item1"; // 加const
// ...
items: const <BottomNavigationBarItem>[ // 保留const
  BottomNavigationBarItem(
    icon: Icon(Icons.build_outlined, size: 22),
    label: myVariable, // 现在可以用了
    activeIcon: Icon(Icons.build),
  ),
],

这种方法适合变量值在编译时就能确定的情况,能保留const带来的性能优化。

内容的提问来源于stack exchange,提问作者xpe

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.02 11:55:39