账号密码登录
微信安全登录
微信扫描二维码登录

登录后绑定QQ、微信即可实现信息互通

手机验证码登录
找回密码返回
邮箱找回 手机找回
注册账号返回
其他登录方式
分享
  • 收藏
    X
    dart 中的 runtimeType 问题?
    • 2020-01-01 00:00
    • 10
    33
    0

    为什么一个是 List<PersonEntity>, 一个是 List<dynamic>

    import 'dart:convert';
    
    const jsonString = '''
    [
    {
      "name": "John Smith",
      "email": "john@example.com"
    }
    ]
    ''';
    
    class PersonEntity {
      String name;
      String email;
    
      PersonEntity({this.name, this.email});
    
      PersonEntity.fromJson(Map<String, dynamic> json) {
        name = json['name'];
        email = json['email'];
      }
    
      Map<String, dynamic> toJson() {
        final Map<String, dynamic> data = new Map<String, dynamic>();
        data['name'] = this.name;
        data['email'] = this.email;
        return data;
      }
    }
    
    main() {
      var parsed = json.decode(jsonString) as List;
      var parsed2 = json.decode(jsonString);
    
      print(parsed
          .map((c) => PersonEntity.fromJson(c))
          .toList()
          .runtimeType); // List<PersonEntity>
      print(parsed2
          .map((c) => PersonEntity.fromJson(c))
          .toList()
          .runtimeType); // List<dynamic>
    }
    
    0
    打赏
    收藏
    点击回答
    您的回答被采纳后将获得:提问者悬赏的 10 元积分
        全部回答
    • 0
    • 娇宠小可爱 普通会员 1楼

      在 Dart 中,runtimeType 是一个关键字,用于指定类型变量在运行时的类型。类型变量用于定义变量的类型,例如在 intdoubleString 等类型上声明变量。以下是一个简单的示例:

      dart int myInt = 42; double myDouble = 3.14159; String myString = "Hello, World!";

      在这个例子中,intdoubleruntimeType,表示它们在运行时的类型是 intdouble,分别代表整型和浮点型。StringruntimeType,表示它在运行时的类型是 String,表示字符串类型。

      runtimeType 的值由下划线 (_) 随机选择,这意味着 myInt 的类型是 intmyDouble 的类型是 double,而 myString 的类型是 String。这种类型变量的使用有助于在运行时检查变量的类型,避免在编译时确定变量的类型,从而提高代码的灵活性和可读性。

      例如,如果你在运行时更改了 int 的类型,你可以使用 dart:io 标准库中的 tryReadLine 方法来检查变量的类型:

      ```dart import 'dart:io';

      void main() { int myInt = 42; double myDouble = 3.14159; String myString = "Hello, World!";

      // Check the type of myInt tryReadLine() { print(myInt); // Output: 42 }

      // Check the type of myDouble tryReadLine() { print(myDouble); // Output: 3.14159 }

      // Check the type of myString tryReadLine() { print(myString); // Output: "Hello, World!" }

      // Type mismatch: cannot convert from 'int' to 'String' print(myInt.toString()); // Output: "42" } ```

      在这个例子中,myInt 的类型在运行时被转换为 String,因此在输出时出现了类型错误。通过使用 tryReadLine,我们可以在运行时检查变量的类型,确保类型转换的正确性。

    更多回答
    扫一扫访问手机版
    • 回到顶部
    • 回到顶部