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

3,925

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!

Share:
3,925
Dadoh
Author by

Dadoh

Updated on December 22, 2022

Comments

  • Dadoh
    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
      nicks101 almost 3 years
      Can you show how you used ! operator? Because this is working for me. ModalRoute.of(context)!.settings.arguments as String
    • Dadoh
      Dadoh almost 3 years
      I've used it exactly like that but I'm getting the same error
    • nicks101
      nicks101 almost 3 years
      What flutter version are you using. If not the latest one, then try upgrading it.
    • Dadoh
      Dadoh almost 3 years
      I'm on stable 2.2.1, the latest one
    • krumpli
      krumpli almost 3 years
      where are you calling ModalRoute.of(context)?.settings.arguments?
    • Dadoh
      Dadoh almost 3 years
      In a didChangeDependencies() function outside the build method
  • Dadoh
    Dadoh almost 3 years
    Still getting an error, Null check operator used on a null value
  • Vikalp
    Vikalp almost 3 years
    Using ! on a null value will throw this exception. Instead use ? like this ModalRoute.of(context)?.settings.arguments as String?