如何在 Flutter 中为 BottomNavigationBarItem 添加徽章?

How to add badge to BottomNavigationBarItem in Flutter?

我有一个 BottomNavigationBar

BottomNavigationBar(
        items: const <BottomNavigationBarItem>[
          BottomNavigationBarItem(
            icon: Icon(Icons.shopping_cart),
            label: 'MyCart',
          ),
          .
          .
          .
          ])

我想为 MyCart 图标添加徽章,我看到 Stack 用于 BottomNavigationBar 的图标是这样的:

new BottomNavigationBarItem(
        title: new Text('Home'),
        icon: new Stack(
          children: <Widget>[
            new Icon(Icons.home),
            new Positioned(  // draw a red marble
              top: 0.0,
              right: 0.0,
              child: new Icon(Icons.brightness_1, size: 8.0, 
                color: Colors.redAccent),
            )
          ]
        ),
      )

但是当我使用它时出现这个错误:

The values in a const list literal must be constants.
Try removing the keyword 'const' from the list literal.

在声明 BottomNavigationBar

中的项目之前删除 const 关键字

MyCart 的类型是 <Widget> 并且您将 BottomNavigationBar 上的 items 属性 设置为类型 List<BottomNavigationBarItem> 将其设置为 List<Widget>。不要将它设置为 List<dynamic> 因为所有 children 必须是 flutter widgets.If 你这样做并再次调用 MyCart() 你将显示到以下 Widget 树:

new BottomNavigationBarItem(
        title: new Text('Home'),
        icon: new Stack(
          children: <Widget>[
            new Icon(Icons.home),
            new Positioned(  // draw a red marble
              top: 0.0,
              right: 0.0,
              child: new Icon(Icons.brightness_1, size: 8.0, 
                color: Colors.redAccent),
            )
          ]
        ),
      )

可能是其他解决方案

您不需要使用 new/const,等等。请参阅下面的代码...

 bottomNavigationBar: BottomNavigationBar(items: [
          BottomNavigationBarItem(
            label: 'aaaaaa',
            icon: Stack(children: <Widget>[
              Icon(Icons.home),
              Positioned(
                // draw a red marble
                top: 0.0,
                right: 0.0,
                child: Icon(Icons.brightness_1, size: 8.0, color: Colors.redAccent),
              )
            ]),
          ),
          BottomNavigationBarItem(
            label: 'dddddd',
            icon: Stack(children: <Widget>[
              Icon(Icons.home),
              Positioned(
                // draw a red marble
                top: 0.0,
                right: 0.0,
                child: Icon(Icons.brightness_1, size: 8.0, color: Colors.redAccent),
              )
            ]),
          )
        ]),