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

Viewed 5090

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.

4 Answers

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(),

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!

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

If you are getting error, Add ? after string

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

If you are still getting error go to the file where you declared productId and change it from String productId to String? productId and add '!' to the productid in the place where you are getting error

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!

Related