Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Flutter BottomNavigationBarItem accepts only Icon and no other widgets?

In our Flutter Cupertino project, we need to show a badge on one of the bottom bar icons. How many articles are already in the shopping cart to be precise.

I've tried different widgets and solutions provided here, but the BottomNavigationBarItem accepts only icon: Icon(..) and nothing else. If I, for example, put icon: Stack(..) instead of the icon: Icon(..), there are error messages shown, for example "Invalid const value..."

Here is some sample code:

class CupertinoStoreHomePage extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return CupertinoTabScaffold(
      tabBar: CupertinoTabBar(
        items: const <BottomNavigationBarItem>[
          BottomNavigationBarItem(
            icon: Icon(CupertinoIcons.home),
            title: Text('Kühlschrank'),
          ),
          BottomNavigationBarItem(
            icon: Icon(CupertinoIcons.profile_circled),
            title: Text('Konto'),
          ),
          BottomNavigationBarItem(
            icon: Icon(CupertinoIcons.shopping_cart),
            title: Text('Warenkorb'),
          ),
        ],
      ),

So if I can not put anything instead of the Icon(..). No other widget, no Stack(..).

Why? How can I put some other widget, like for example Badge(..):

badges: ^1.0.2
import 'package:badges/badges.dart';

This question is different from the possible duplicate, because I already tried the solution posted there and still can not use Stack(..) but only Icon(..).

like image 952
Andrey Bulgakow Avatar asked Dec 31 '22 22:12

Andrey Bulgakow


1 Answers

I tried reproducing the problem, but it does work after changing a few things. First of all the icon property accepts a Widget and therefore not only an Icon, so this is not the problem.

I did notice however, in items: const <BottomNavigationBarItem>[ you should remove the const keyword as it is not necessary and also not constant.

And lastly, you need to add a tab builder to CupertinoTabScaffold this basically returns what's displayed above the bottom navigation bar.

Your final code then looks like this:

return CupertinoTabScaffold(
      tabBuilder: (BuildContext context, int i) {
        return CupertinoActivityIndicator();
      },
      tabBar: CupertinoTabBar(
        items: <BottomNavigationBarItem>[
          BottomNavigationBarItem(
            icon: Badge(
              badgeContent: Text('3'),
              child: Icon(Icons.settings),
            ),
            title: Text('Kühlschrank'),
          ),
          BottomNavigationBarItem(
            icon: Icon(CupertinoIcons.profile_circled),
            title: Text('Konto'),
          ),
          BottomNavigationBarItem(
            icon: Icon(CupertinoIcons.shopping_cart),
            title: Text('Warenkorb'),
          ),
        ],
      ),
    );
like image 103
Noodles Avatar answered May 22 '23 09:05

Noodles