flutterdart

How to handle the error type 'Null' is not a subtype of type 'bool' in type cast?


How to write it properly to avoid Unhandled Exception: type 'Null' is not a subtype of type 'bool' in type cast?

    final reLoadPage = await ...; // can be null

    if (reLoadPage as bool ?? false) { // error
        ...
    }

Solution

  • In general, you can coerce the value from bool? to bool by using the null coalescing operator to provide a default value:

    final boolValue = nullableBoolValue ?? false;
    

    But in your case, you don't actually have to do this. Just check if the nullable value is equal to true:

    final reLoadPage = await ...;
    if (reLoadPage == true) {
      ...
    }