i need to evaluate what type is a variable to make some switch,there are any way to evaluate a varible to get his type, like val() or something similar. i need to do something for integers and other for string.
i alreaedy try to using a switch, like this,
switch (selector) { case int : print('value is a integer'); break; case String: print('value is a String'); break;
}
but how i do this, if switch can allow compare mixed type of vars?
thank you
To check the type of a variable in Flutter and Dart, you can use the runtimeType property.
It is easy to check if a number is an int , just do value is int . The slightly harder task is to check whether a double value has an integer value, or no fractional part. There is no simple function answering that, but you can do value == value. roundToDouble() .
To check whether a string is a numeric string, you can use the double. tryParse() method. If the return equals null then the input is not a numeric string, otherwise, it is. Hope this helps.
Dart objects have runtimeType property which returns Type . 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 .
Calling a variable inside string is extremely easy in Flutter. You just need to use the dollar syntax as given below. Here $value represents an already defined variable named value. Still unclear? See the complete Flutter example given below.
Another way to find the type of a variable in Dart/Flutter is by using is operator which is similar to instanceof operator in JavaScript. Here again pay attention to the int inside the ‘if’ condition which is not a string.
Here $value represents an already defined variable named value. Still unclear? See the complete Flutter example given below.
Importantly, this variable must be a String forever. You cannot re-assign the variable as an integer. If you did want to create a variable that's more dynamic, you'd use the dynamic keyword. We'll see examples of that in a later lesson.
You can use the keyword is
or switch over runtimeType
:
dynamic foo = 42; if (foo is int) { print("Hello"); } switch (foo.runtimeType) { case int: { print("World"); } }
Consider using is
instead of directly using runtimeType
. As is
works with subclasses. While using runtimeType
is a strict comparison.
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