【问题标题】:Force Nullable String/Json in New Flutter version (null safety)在新的 Flutter 版本中强制为 Nullable String/Json(null 安全)
【发布时间】:2025-12-14 06:15:01
【问题描述】:

我是 Flutter 的新手,正在开发一款可供公共用户或公寓居住者使用的应用。 新的颤振迫使我添加必需的或其他空安全的东西。

我得到了错误类型“I/flutter (12174): type 'Null' is not a subtype of type 'String'

有没有办法在不降级我的颤振的情况下使用可为空的字符串?

Json/API 输出

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

模型.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

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

【问题讨论】:

    标签: android arrays json flutter api


    【解决方案1】:

    使用可以为空的值更改模型类声明并删除后期关键字

    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,
        };
      }
    }
    

    【讨论】:

      【解决方案2】:

      请参考以下代码

      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,
          };
        }
      }
      
      

      【讨论】: