I had Project, which was working very well. I upgraded it to null safety.
Now I'm getting the Expected a value of type 'Map<String, String?>', but got one of type 'Null
.
Here is the code before the upgrading to null safety:
final Map<String, String> args = ModalRoute.of(context).settings.arguments;
which is working fine.
And here is the code after upgrading to null safety.
final Map<String, String?> args =
ModalRoute.of(context)!.settings.arguments as Map<String, String?>;
which gives the error Dose any know why? and how to fix it. Thanks in advance.
CodePudding user response:
Your ModalRoute.of(context)
may be null for that reason you used !
on it so it may cause ModalRoute.of(context)!.settings.arguments
be null but you expect non-null Map
, so change this:
final Map<String, String?> args =
ModalRoute.of(context)!.settings.arguments as Map<String, String?>;
to this:
final Map<String, String?>? args =
ModalRoute.of(context)?.settings.arguments as Map<String, String?>?;
CodePudding user response:
no need to use ?
as you already initialize it
you can try to use toString
with json decode
final args = json.decode(ModalRoute.of(context)!.settings.arguments.toString()) ;
CodePudding user response:
I changed the code:
final Map<String, String?> args = ModalRoute.of(context)!.settings.arguments as Map<String, String?>;
to
Map? args = {};
args = ModalRoute.of(context)!.settings.arguments as Map?;
And it is working. Can someone please explain, what was the cause of the error? thank you