Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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.
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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Json/API Output

"status": true,
"message": "Sign Up Success",
"data": [
    {
        "id": "2042",
        "email": "user@domain.com",
        "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');
    }

>Solution :

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,
    };
  }
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading