I have a question related to the state.extra in Flutter.
I want to pass null value to the player’s profile page, so it will display 0.
Right now I have declared extra that doesn’t allow me to pass null value.
What could be the best solution for this problem?
GoRoute(
path: 'settings',
pageBuilder: (context, state) {
final map = state.extra as Map<String, dynamic>;
final score = map['score'] as Score;
return buildMyTransition<void>(
child: SettingsScreen(
score: score,
key: const Key('settings'),
),
color: context.watch<Palette>().backgroundPlaySession,
);
},
Error message
Exception has occurred.
_TypeError (type ‘Null’ is not a subtype of type ‘Map<String, dynamic>’ in type cast)
2
Answers
You are trying to cast a null value, here state.extra is null. Make sure to have state.extra some value or add a check of not null condition
Your error is saying that
state.extra
could return anull
value, and if that was the case then the code execution would be "null as Map<String, dynamic>;
" hence the error.In this case you need to add
?
to make it null-safe:and now since
map
could return null, you need to adjust yourscore
to check if the value is null and what should it be if so. for example:In this example, you are setting
score = 0
if the result ofmap?['score']
is null