Below is the code where I am first printing the type of myVar. It returns List<dynamic>
in the console. But when I compare its type in a if
condition, it does not pass this condition.
print(myVar.runtimeType);
if (myVar.runtimeType is List<dynamic>) {
print("Yes");
}
What's wrong here?
To check the type of a variable in Flutter and Dart, you can use the runtimeType property.
To check whether the object has a certain type, use == operator. Unlike is , it will only return true if compared to an exectly same type, which means comparing it with its super class will return false .
Dart dynamic type In Dart, when a variable is declared as a dynamic type, it can store any value, such as int and float . The value of a dynamic variable can change over time within the program.
runtimeType
is of type Type
and never going to be List
or int
.
The is
operator automatically compares types
.
Also when writing a type, if you leave the generic parameter empty, it will be read as a dynamic. for example List
and List<dynamic>
have the same type.
if (myVar is List) {
print("Yes");
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With