【问题标题】:Why <type 'Null' is not a subtype of type 'String'> error doesn't appear in debug (Flutter)为什么 <type \'Null\' is not a subtype of type \'String\'> 错误没有出现在调试中(Flutter)
【发布时间】:2022-11-19 00:09:20
【问题描述】:

所以我在 Flutter 上开发应用程序,并在下面编写了这段代码。我发现我们的 BE 有时不会返回 language 字段,因此需要将其标记为可选。但问题是,为什么当我在调试模式下使用 vscode 时,它​​什么也没说,但是当我创建 ipa 或 apk 文件,在物理设备上运行它时,它会在尝试“序列化”这个模型时抛出错误?我也附上了错误的屏幕截图。

class User {
  late int id;
  late String firstName;
  late String lastName;
  late String? birthdate;
  late bool showBirthDate;
  late UserStatus status;
  late String description;
  late String phone;
  late String email;
  late String language;
  late String image;

  User({
    required this.id,
    required this.firstName,
    required this.lastName,
    required this.birthdate,
    required this.showBirthDate,
    required this.status,
    required this.description,
    required this.phone,
    required this.email,
    required this.language,
    required this.image,
  });

  User.fromJson(Map<String, dynamic> json) {
    id = json['id'];
    firstName = json['firstName'];
    lastName = json['lastName'];
    birthdate = json['date_of_birth'];
    showBirthDate = json['show_birth_date'] == 10;
    status = UserStatus.fromStaus(json['status']);
    description = json['description'];
    phone = json['phone'];
    email = json['email'];
    language = json['language'];
    image = json['image'];
  }
}

我试图弄清楚如何在调试模式下出现 <type 'Null' is not a subtype of type 'String'> 错误。

【问题讨论】:

    标签: json flutter dart visual-studio-code decoding


    【解决方案1】:

    在加载 json 时检查 null 和类型转换

     id = int.parse(json['id'].toString()) ?? 0 ;
        firstName = json['firstName'].toString ?? 'First';
        lastName = json['lastName'].toString ?? 'Last';
       
    

    【讨论】:

    • 我完全明白如何解决它。我的问题是“如何调试它”。在调试模式下,应用程序对此字段不做任何说明。但是当我创建 apk 或 ipa 文件时,它开始抛出它。
    猜你喜欢
    • 2023-02-17
    • 2021-10-22
    • 2022-09-29
    • 2023-01-12
    • 2020-04-12
    • 1970-01-01
    • 1970-01-01
    • 2020-02-14
    • 2022-11-20
    相关资源
    最近更新 更多