Dart : How to Check if a variable type is String
Instead of
if(T is String)
it should be
if(_val is String)
The is
operator is used as a type-guard at run-time which operates on identifiers (variables). In these cases, compilers, for the most part, will tell you something along the lines of T refers to a type but is being used as a value
.
Note that because you have a type-guard (i.e. if(_val is String)
) the compiler already knows that the type of _val
could only ever be String
inside your if
-block.
Should you need to explicit casting you can have a look at the as
operator in Dart, https://www.dartlang.org/guides/language/language-tour#type-test-operators.
Use .runtimeType
to get the type:
void main() {
var data_types = ["string", 123, 12.031, [], {} ];`
for(var i=0; i<data_types.length; i++){
print(data_types[i].runtimeType);
if (data_types[i].runtimeType == String){
print("-it's a String");
}else if (data_types[i].runtimeType == int){
print("-it's a Int");
}else if (data_types[i].runtimeType == [].runtimeType){
print("-it's a List/Array");
}else if (data_types[i].runtimeType == {}.runtimeType){
print("-it's a Map/Object/Dict");
}else {
print("\n>> See this type is not their .\n");
}
}}