How to check Type of a Variable in Dart or Flutter

How to check Type of a Variable in Dart or Flutter

There are couple ways to determine the type of a variable in Dart/Flutter.

Similar to the way developers use ‘typeof‘ operator in JavaScript, we can use runtimeType in Dart.

example:

void main() {
  var myNum = 10;
  var myNum2 = 10.0;
  var myString = 'Hello World';
  var myBool = true;
  var myArray = [1, 2, 3];
  var person = {'id': 1, 'name': 'John Doe'};

  print(myNum.runtimeType);
  print(myNum2.runtimeType);
  print(myString.runtimeType);
  print(myBool.runtimeType);
  print(myArray.runtimeType);
  print(person.runtimeType);
}

Output:

int
double
String
bool
List<int>
_InternalLinkedHashMap<String, Object>

Pay attention to the way we initialized the variables myNum and myNum2. If you want to create a variable using var keyword and wants to make it of type double, you need to add ‘.’ else it will considered as int.

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.

example:

void main() {
  var myNum = 10;

  if (myNum is int) {
    print('myNum is an integer');
  }
}

Output:

myNum is an integer

Here again pay attention to the int inside the ‘if’ condition which is not a string.

Leave A Comment

Your email address will not be published. Required fields are marked *