skip to Main Content

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


  1. 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

    Login or Signup to reply.
  2. Your error is saying that state.extra could return a null 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:

    final map = state.extra as Map<String, dynamic>?; //can now be map = null
    

    and now since map could return null, you need to adjust your score to check if the value is null and what should it be if so. for example:

    final score = map?['score'] as Score ?? 0; 
    

    In this example, you are setting score = 0 if the result of map?['score'] is null

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search