简体   繁体   English

在新的 Flutter 版本中强制为空字符串/Json(空安全)

[英]Force Nullable String/Json in New Flutter version (null safety)

Im New In Flutter, and developing an app that can be used by public user or apartment occupants.我是 Flutter 的新手,正在开发可供公共用户或公寓居住者使用的应用程序。 The new flutter force me to add required or other null safety thing.新的 flutter 迫使我添加所需的或其他 null 安全物品。

and i got error type 'I/flutter (12174): type 'Null' is not a subtype of type 'String'我得到错误类型'I/flutter(12174):类型'Null'不是'String'类型的子类型

is there anyway to use nullable String without downgrading my flutter?无论如何都可以在不降级我的 flutter 的情况下使用可为空的字符串?

Json/API Output json/API Output

"status": true,
"message": "Sign Up Success",
"data": [
    {
        "id": "2042",
        "email": "user@domain.com",
        "id_apartment": null,
    }
]

Model.dart Model.dart

class UserModel {
  late String id;
  late String email;
  late String id_apartment,;

  UserModel({
    required this.id,
    required this.email,
    required this.id_apartment,
  });

  UserModel.fromJson(Map<String, dynamic> json) {
    id = json['id'];
    email = json['email'];
    id_apartment= json['id_apartment'];
  }

  Map<String, dynamic> toJson() {
    return {
      'id': id,
      'email': email,
      'id_apartment': id_apartment,
    };
  }
}

Service.dart服务.dart

if (response.statusCode == 200) {
      var data = jsonDecode(response.body)['data'];
      UserModel user = UserModel.fromJson(data[0]);
      
      return user;
    } else {
      throw Exception('Sign Up Failed');
    }

change your model class declaration with null-able value and remove the late keywords使用可为空的值更改您的 model class 声明并删除后期关键字

class UserModel {
  String? id;
  String? email;
  String? id_apartment,;

  UserModel({
    required this.id,
    required this.email,
    required this.id_apartment,
  });

  UserModel.fromJson(Map<String, dynamic> json) {
    id = json['id'];
    email = json['email'];
    id_apartment= json['id_apartment'];
  }

  Map<String, dynamic> toJson() {
    return {
      'id': id,
      'email': email,
      'id_apartment': id_apartment,
    };
  }
}

Please refer to below code请参考以下代码

id = json['id'] ?? "";
email = json['email'] ?? "";
id_apartment= json['id_apartment'] ?? "";
class UserModel {
  late String id;
  late String email;
  late String id_apartment;

  UserModel({
    required this.id,
    required this.email,
    required this.id_apartment,
  });

  UserModel.fromJson(Map<String, dynamic> json) {
    id = json['id'] ?? "";
    email = json['email'] ?? "";
    id_apartment= json['id_apartment'] ?? "";
  }

  Map<String, dynamic> toJson() {
    return {
      'id': id,
      'email': email,
      'id_apartment': id_apartment,
    };
  }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM