how to migrate a big project to null safety for handling json data in flutter

Issue

I didn’t worked in flutter for couple of months and when I open after so long so many errors came looking at those I just upgraded all packages to the latest version and after upgrading I came to know it will now only work with null safety as flutter is now null safety and do I need to convert all my variables to null safety as sometimes null data comes in api i’m not getting how can I do every variable null check there are vast classes

here is my previous code where i just manually did LoginResponse variables to nullcheck

    LoginResponse loginResponseFromJson(String str) => LoginResponse.fromJson(json.decode(str));

String loginResponseToJson(LoginResponse data) => json.encode(data.toJson());

class LoginResponse {
  LoginResponse({
    this.loggedIn,
    this.user,
  });

  bool? loggedIn;
  User ? user;

  factory LoginResponse.fromJson(Map<String, dynamic> json) => LoginResponse(
    loggedIn: json["loggedIn"],
      user : json['user'] == null ? null : new User.fromJson(json['user']) ,

  );

  Map<String, dynamic> toJson() => {
    "loggedIn": loggedIn,

    "user": user == null ?null : user,
  };
}

class User {
  User({
     this.id,
    this.name,
    this.emailId,
    this.contactNumber,
    this.password,
    this.authToken,
    this.roles,
    this.companyId,
    this.storeName,
    this.region,
  });

  String id;
  String name;
  String emailId;
  dynamic contactNumber;
  String password;
  String authToken;
  String roles;
  String companyId;
  String storeName;
  String region;

  factory User.fromJson(Map<String, dynamic> json) => User(
    id: json["id"],
    name: json["name"],
    emailId: json["emailId"],
    contactNumber: json["contactNumber"],
    password: json["password"],
    authToken: json["authToken"],
    roles: json["roles"],
    companyId: json["companyId"],
    storeName: json["storeName"],
    region: json["region"],
  );

  Map<String, dynamic> toJson() => {
    "id": id,
    "name": name,
    "emailId": emailId,
    "contactNumber": contactNumber,
    "password": password,
    "authToken": authToken,
    "roles": roles,
    "companyId": companyId,
    "storeName": storeName,
    "region": region,
  };
}

it works when I put nullcheck like in the first class please tell me whether there is any process to convert all the things without doing it manually

Solution

You can checkout the dart null safety auto migration process by using migration tool https://dart.dev/null-safety/migration-guide.

But I will recommend you to not use this auto migration process because it is risky. It would be good if you can migrate your project file by file manually and ofcourse it will take time but it is safer option.

Answered By – Zakaria Hossain

Answer Checked By – David Goodson (FlutterFixes Volunteer)

Leave a Reply

Your email address will not be published. Required fields are marked *