'"type 'Null' is not a subtype of type 'String' in type cast" error in ModalRoute.of(context).settings

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.



Solution 1:[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:[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!

Solution 3:[3]

final productId = ModalRoute.of(context)?.settings.arguments as String

just add ? to end of this line like that: final productId = ModalRoute.of(context)!.settings.arguments as String? It works!

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Sarthak Raval
Solution 2 Dadoh
Solution 3 TuGordoBello