Search code examples
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

  • The correct way is to check first whether the reLoadPage variable is bool or not so that you can check its type.

    final reLoadPage = null;
    if((reLoadPage is bool) ? reLoadPage : false){
    print("Can reLoadPage");
    }
    else{
    print("Can Not reLoadPage");
    }