flutter evaluate if var is integer or string

Create this extension:

extension EvaluateType on Object? {
  bool get isInt => this is int;
  bool get isString => this is String;
}

Usage:

void main() {
  Object? foo;
  
  foo = 0;
  print(foo.isInt); // true
  print(foo.isString); // false
}

It's very simple:

dynamic a = "hello";
if (a.runtimeType == int)
  print("a is int");
else if (a.runtimeType == String) 
  print("a is String");

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.


You can use something like :

if(selector.runtimeType == int) print("Hello")

Tags:

Flutter