问题描述
我想检查http
请求的响应是否匹配特定的datatype
(= List<dynamic
)。
case 200:
var responseJson = json.decode(response.body);
print(responseJson['results'].runtimeType); // Output: I/Flutter (13862): List<dynamic>
print(responseJson['results'].runtimeType is List<dynamic>); // Output: I/Flutter (13862): false
if (responseJson['results'].runtimeType is List<dynamic> &&
responseJson['results'].length > 0) {
return responseJson;
}
throw NotFoundException('Result is empty...');
我很困惑...为什么打印false
? runtimType
的输出显示List<dynamic>
,因此应为true
...
解决方法
您仅应将runtimeType
用于调试目的,因为此属性将在运行时返回对象的实际类型,并且不能用于检查给定类型是否与另一类型兼容。
is
运算符是用于检查类型的正确运算符,但您在针对runtimeType
使用它的情况下返回了Type
对象。相反,您应该只使用它:responseJson['results'] is List<dynamic>
。
这将检查类型是否与List<dynamic>
兼容。您也可以像这样简单一些:responseJson['results'] is List