flutter 如何使用switch case 来判断类型
在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/dkDK 著作权归作者所有。请勿转载和采集!