Home > Back-end >  BottomNavigationBar index error (flutter)
BottomNavigationBar index error (flutter)

Time:07-03

I'm having an app with a bottom navigation bar:

 Widget build(BuildContext context) {

    print("current tab");
    print(currentTab?.index); //<-- It's work!! -->

    return BottomNavigationBar(
        selectedItemColor: _colorTabMatching(currentTab!),
        selectedFontSize: 13,
        unselectedItemColor: Colors.grey,
        type: BottomNavigationBarType.fixed,
        currentIndex: currentTab?.index, //<-- does not work!! -->
        items: [
          _buildItem(TabItem.POSTS),
          _buildItem(TabItem.ALBUMS),
          _buildItem(TabItem.TODOS),
        ],
        onTap: (int index) => onSelectTab!(
            TabItem.values[index]
        )
    );

Error:

The argument type 'int?' can't be assigned to the parameter type 'int'.

Now I need to pass the index, but I see an error. Why?

enter image description here

CodePudding user response:

currentIndex doesn't take nullable int.

Doing currentTab?.index means it is accepting null value. You can provide default value as 0 on null case like,

currentIndex: currentTab?.index?? 0 

More about null-safety and currentIndex

CodePudding user response:

I'm comming from C# background, and judging only by the error message, basically what is happening is, property currentIndex is supposed to be of type int. Problem with your code is that currentTab is of type TabItem? meaning nullable TabItem. Meaning it can be either null or TabItem object. Using the syntax currentTab?.index is basically saying: "If currentTab is null, just return null. If it is not null, then return me the index value.". Dart syntax is veeery simmilar to C#'s, and I checked that this code will work:

currentIndex: currentTab?.index ?? 0

Basically what this code does, is: "If currentTab is null, then return the value 0. If it is not null, then return me the index value.". See the diference? You basically have to manually handle the situation where the currentTab is equal to null.

Disclaimer: I did not try this code, however as I said, C# and Dart are similar (as far as syntax goes), and I double checked on the internet that Dart does offer these syntax features

Edit: Or you can handle currentTab being null using some Flutter way, before rendering, however, as I said before, I don't know Dart/Flutter.

  • Related