Dart 中的运行时类型检查 - 检查列表

Runtime type checking in Dart - Check for List

我想检查 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...');

我很困惑...为什么它打印 falseruntimType 的输出显示 List<dynamic> 所以它应该是 true...

您应该只将 runtimeType 用于调试目的,因为此 属性 returns 对象在运行时的实际类型,不能用于检查给定类型是否与另一种。

is 运算符是您用于检查类型的正确运算符,但您将它用于 runtimeType,returns 一个 Type 对象。相反,您应该像这样使用它:responseJson['results'] is List<dynamic>.

这将检查类型是否与 List<dynamic> 兼容。你也可以这样做更简单一点:responseJson['results'] is List