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

admin2025-04-15  0

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
        ...
    }

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
        ...
    }
Share Improve this question asked Feb 4 at 12:29 rozerrorozerro 7,23614 gold badges64 silver badges119 bronze badges 3
  • 1 i prefer if (bool.tryParse("$reLoadPage") == true) – Md. Yeasin Sheikh Commented Feb 4 at 14:07
  • @Md.YeasinSheikh looks pretty convenient and short – rozerro Commented Feb 4 at 16:37
  • What is the actual type of reLoadPage? Is it bool?? Is it dynamic? Is it Object?? Is it something else entirely? – Abion47 Commented Feb 4 at 18:09
Add a comment  | 

4 Answers 4

Reset to default 1

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");
}

if reLoadPage type is bool? then you don't have to define as bool after the variable name, it's unnecessary.

you can write like below
if (reLoadPage ?? false)

or with as bool
if (reLoadPage as bool? ?? false)

if reLoadPage type is dynamic then
if((reLoadPage is bool) ? reLoadPage : false)

I hope the answers have been sufficient. However, as a contribution, with this answer:

if((reLoadPage is bool) ? reLoadPage : false)

This answer:

if(reLoadPage ?? false) // or (reloadPage as bool?) ?? false

It has the same value

A small reminder: If you are returning a boolean value within a condition using if and else, you should not forget that conditional statements like if and else already evaluate to a boolean value.

Example:

bool myValue = otherValue == true ? true : false;

bool myValue = otherValue ? true : false;

bool myValue = otherValue;

These three have the same value.

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) {
  ...
}
转载请注明原文地址:http://www.anycun.com/QandA/1744719745a86677.html