"type 'Null' is not a subtype of type 'String' in type cast" error in ModalRoute.of(context).settings
Solution 1
I also have the same problem and this is my code and works as a charm.
final productId = ModalRoute.of(context)!.settings.arguments as String?;
if (productId != null) {
_editedProduct =
Provider.of<Products>(context, listen: false).findById(productId);
_initValues = {
'title': _editedProduct.title,
'description': _editedProduct.description,
'price': _editedProduct.price.toString(),
Solution 2
I somewhat managed to make it at least compile changing
final productId = ModalRoute.of(context)?.settings.arguments as String;
to
final String? productId = ModalRoute.of(context)!.settings.arguments.toString() ?? "";
It still throws me an error:
Warning: Operand of null-aware operation '??' has type 'String' which excludes null.
but it seems to be working for now. If you have any suggestions to make it work without complaints go ahead though!
Dadoh
Updated on December 22, 2022Comments
-
Dadoh over 1 year
I'm trying to pass an argument through Navigator like this:
Navigator.of(context).pushNamed(EditProductScreen.routeName, arguments: id);
But when trying to retrieve it using
final productId = ModalRoute.of(context)?.settings.arguments as String;
I'm getting this error: type 'Null' is not a subtype of type 'String' in type cast. I've also tried using the bang!
operator but with no luck.-
nicks101 almost 3 yearsCan you show how you used
!
operator? Because this is working for me.ModalRoute.of(context)!.settings.arguments as String
-
Dadoh almost 3 yearsI've used it exactly like that but I'm getting the same error
-
nicks101 almost 3 yearsWhat flutter version are you using. If not the latest one, then try upgrading it.
-
Dadoh almost 3 yearsI'm on stable 2.2.1, the latest one
-
krumpli almost 3 yearswhere are you calling ModalRoute.of(context)?.settings.arguments?
-
Dadoh almost 3 yearsIn a didChangeDependencies() function outside the build method
-
-
Dadoh almost 3 yearsStill getting an error,
Null check operator used on a null value
-
Vikalp almost 3 yearsUsing ! on a null value will throw this exception. Instead use ? like this ModalRoute.of(context)?.settings.arguments as String?