Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dart : How to Check if a variable type is String

Tags:

dart

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>();
like image 853
MistyD Avatar asked Jan 22 '19 05:01

MistyD


People also ask

How do you check a variable type in Dart?

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 .

How do you check Dart strings?

To check if a string contains other string in Dart, call contains() method on this string and pass the other string as argument. contains() method returns returns a boolean value of true if this string contains the other string, or false if the this string does not contain other string.

Is string primitive in Dart?

Dart is a statically typed language which means while declaring a variable, we need to specify what kind of data that variable is going to store. A variable without value has null value by default. There are basically int , double , boolean and string primitive Data Types in Dart.


2 Answers

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.

like image 119
ethane Avatar answered Sep 21 '22 08:09

ethane


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");
    } 
}}
like image 38
subarna sahoo Avatar answered Sep 22 '22 08:09

subarna sahoo