Flutter中如何为BottomNavigationBarItem添加徽章?报错求解
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
constlets the list accept both constant and non-constantBottomNavigationBarItementries. - Adding
constto theStack'schildrenlist is optional but recommended, as it optimizes the static parts of the badge widget.
内容的提问来源于stack exchange,提问作者Baran Gungor

