The argument type 'GlobalKey<NavigatorState>?' can't be assigned to the parameter type'GlobalKey<NavigatorState>'

Viewed 1128

I am getting this error:

The argument type 'GlobalKey<NavigatorState>?' can't be assigned to
the parameter type'GlobalKey<NavigatorState>'

.dart(argument_type_not_assignable)
Map<BottomNavItem, GlobalKey<NavigatorState>> navigatorKeys

I do believe that I am passing the correct thing. But where does this question mark at the end shows up?

 Widget _buildOffStageNavigatorItem(
    BottomNavItem currentItem,
    bool isSelected,
  ) {
    return Offstage(
      offstage: !isSelected,
      child: TabNavigator(
        item: currentItem,
        navigatorKey: navigatorKeys[currentItem],
      ),
    );
  }

final Map<BottomNavItem, GlobalKey<NavigatorState>> navigatorKeys = {
    BottomNavItem.home: GlobalKey<NavigatorState>(),
    BottomNavItem.scorecard: GlobalKey<NavigatorState>(),
    BottomNavItem.rewards: GlobalKey<NavigatorState>(),
    BottomNavItem.orders: GlobalKey<NavigatorState>(),
  };

pls help

2 Answers

Maps always return a nullable object. This is because there is no way to guarantee that the key you are accessing is there without limiting the map object. If you know for sure the data is in there

navigatorKey: navigatorKeys[currentItem]!,

If you don't know for sure

var item = navigatorKeys[currentItem]
if (item == null) // Do something
return Offstage(
      offstage: !isSelected,
      child: TabNavigator(
        item: currentItem,
        navigatorKey: navigatorKeys[currentItem],
      ),
    );

this fixes it. navigatorKey: navigatorKeys[currentItem]!,

Basically I was assigning a nullable to non nullable

Related