Home > Net >  Force Nullable String/Json in New Flutter version (null safety)
Force Nullable String/Json in New Flutter version (null safety)

Time:12-09

Im New In Flutter, and developing an app that can be used by public user or apartment occupants. The new flutter force me to add required or other null safety thing.

and i got error type 'I/flutter (12174): type 'Null' is not a subtype of type 'String'

is there anyway to use nullable String without downgrading my flutter?

Json/API Output

"status": true,
"message": "Sign Up Success",
"data": [
    {
        "id": "2042",
        "email": "[email protected]",
        "id_apartment": null,
    }
]

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

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

CodePudding user response:

change your model class declaration with null-able value and remove the late keywords

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

CodePudding user response:

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

  • Related