Andrew
Andrew

Reputation: 145

BottomNavigationBar index error (flutter)

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

Upvotes: 0

Views: 226

Answers (2)

TDiblik
TDiblik

Reputation: 622

I'm coming 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 very similar 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 difference? 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.

Upvotes: 1

Md. Yeasin Sheikh
Md. Yeasin Sheikh

Reputation: 63819

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

Upvotes: 2

Related Questions