MistyD
MistyD

Reputation: 17223

Dart : How to Check if a variable type is String

I have this code . The class is generic and when I instantiate it by passing a String Type. The variable becomes a string type. However the statement

if(_val is String){
}

doesnt seem to be true. Any idea why ?

This is the full code:

    class foo<T>{
    T _val;
    QVar()
    {
         //Read the value from preferences
         if(_val is String){
            ... //Does not come in here!!
         }
    }
  }

 a   = new foo<String>();

Upvotes: 40

Views: 49904

Answers (2)

subarna kumar sahoo
subarna kumar sahoo

Reputation: 137

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

Upvotes: 11

&#196;lskar
&#196;lskar

Reputation: 2577

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.

Upvotes: 68

Related Questions