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

Mat*_*ias 2 types dynamic instanceof dart

我想检查请求的响应是否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...');
Run Code Online (Sandbox Code Playgroud)

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

jul*_*101 7

您应该仅用于runtimeType调试目的,因为此属性在运行时返回对象的实际类型,并且不能用于检查给定类型是否与其他类型兼容。

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

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