Flutter 类型判断:使用 switch case 和 runtimeType
在 Flutter 中,可以使用'runtimeType'属性获取对象的类型,然后使用'switch case'语句来判断类型。示例代码如下:
void main() {
var obj1 = 'hello';
var obj2 = 123;
var obj3 = true;
switch (obj1.runtimeType) {
case String:
print('obj1 is a String');
break;
case int:
print('obj1 is an int');
break;
case bool:
print('obj1 is a bool');
break;
default:
print('obj1 is of unknown type');
}
switch (obj2.runtimeType) {
case String:
print('obj2 is a String');
break;
case int:
print('obj2 is an int');
break;
case bool:
print('obj2 is a bool');
break;
default:
print('obj2 is of unknown type');
}
switch (obj3.runtimeType) {
case String:
print('obj3 is a String');
break;
case int:
print('obj3 is an int');
break;
case bool:
print('obj3 is a bool');
break;
default:
print('obj3 is of unknown type');
}
}
输出结果:
obj1 is a String
obj2 is an int
obj3 is a bool
原文地址: https://www.cveoy.top/t/topic/kGNw 著作权归作者所有。请勿转载和采集!