Search code examples
flutterdartdart-null-safety

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


Solution

  • 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