Vincent
Vincent

Reputation: 3304

Modify model to adapt to null fafety

I migrated to null safety, environment: sdk: ">=2.12.0 <3.0.0"

But my ImageModel report error.

class ImageModel {
    ImageModel({
        this.total,
        this.totalHits,
    });

    int total;
    int totalHits;

    factory ImageModel.fromJson(Map<String, dynamic> json) => ImageModel(
        total: json["total"],
        totalHits: json["totalHits"],
    );

    Map<String, dynamic> toJson() => {
        "total": total,
        "totalHits": totalHits,
    };
}

Should I just add required to this.total and this.totalHits as the vscode suggest?

But this.total and this.totalHits are always return from server json.

Upvotes: 0

Views: 37

Answers (1)

Karim
Karim

Reputation: 1010

I would recommend you always to make all fields (except ids) nullable.

You never know what will happen in some months in the backend that one of those fields could start being nullable.

And some of ur users will never update the app.

Upvotes: 1

Related Questions