Flutter评估变量是整数还是字符串

40
我需要评估变量的类型以进行一些开关操作,有没有办法评估一个变量以获取其类型,例如val()或类似的东西。我需要为整数执行某些操作,为字符串执行其他操作。
我已经尝试使用switch,像这样:
 switch (selector) {
case  int :
  print('value is a integer');
    break;
case  String:
    print('value is a String');
   break;

但是如果switch语句可以允许比较混合类型的变量,我应该如何做呢?谢谢。

4个回答

77

您可以使用关键词 is 或切换 runtimeType

dynamic foo = 42;
if (foo is int) {
  print("Hello");
}
switch (foo.runtimeType) {
  case int: {
    print("World");
  }
}

考虑使用is代替直接使用runtimeType,因为is可以处理子类。而使用runtimeType则是严格比较。


10
您可以使用以下方式:
if(selector.runtimeType == int) print("Hello")

3
非常简单:
dynamic a = "hello";
if (a.runtimeType == int)
  print("a is int");
else if (a.runtimeType == String) 
  print("a is String");

1
创建这个扩展程序:
extension EvaluateType on Object? {
  bool get isInt => this is int;
  bool get isString => this is String;
}

用法:

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接