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

Flutter中如何为BottomNavigationBarItem添加徽章?报错求解

Fix: "Values in a const list literal must be constants" Error for BottomNavigationBar Badge

Hey there! Let's break down why this error pops up and how to fix it quickly.

Why the Error Happens

Your original BottomNavigationBar uses a const list for the items property, like this:

items: const <BottomNavigationBarItem>[...]

But when you add the Stack and Positioned widgets to create the badge, those components can't be marked as const—either their constructors don't support const, or their layout parameters aren't compile-time constants. This makes the entire "MyCart" BottomNavigationBarItem a non-constant value, which clashes with the const list's requirement that all entries are constants.

The Simple Fix

Just remove the const keyword from the outer items list. You can still keep const on individual BottomNavigationBarItem entries that don't need dynamic widgets (like the badge) to retain small performance optimizations.

Here's the updated working code:

BottomNavigationBar(
  items: <BottomNavigationBarItem>[ // Removed the top-level const here
    BottomNavigationBarItem(
      icon: Stack(
        children: const <Widget>[ // We can add const here since child widgets are static
          Icon(Icons.shopping_cart),
          Positioned(
            top: 0.0,
            right: 0.0,
            child: Icon(Icons.brightness_1, size: 8.0, color: Colors.redAccent),
          )
        ],
      ),
      label: 'MyCart',
    ),
    // Keep const for other static navigation items
    const BottomNavigationBarItem(
      icon: Icon(Icons.home),
      label: 'Home',
    ),
    // Add your remaining navigation items here...
  ],
)

Quick Tips

  • Removing the top-level const lets the list accept both constant and non-constant BottomNavigationBarItem entries.
  • Adding const to the Stack's children list is optional but recommended, as it optimizes the static parts of the badge widget.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.09 13:37:51