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
...
}
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) {
...
}
if (bool.tryParse("$reLoadPage") == true)
– Md. Yeasin Sheikh Commented Feb 4 at 14:07reLoadPage
? Is itbool?
? Is itdynamic
? Is itObject?
? Is it something else entirely? – Abion47 Commented Feb 4 at 18:09