Home > Software engineering >  flutter error : Expected a value of type 'int' but got one of type 'Null'
flutter error : Expected a value of type 'int' but got one of type 'Null'

Time:01-29

response body from the .NET Core 6 API :

[{"establishmentId":1,"establishmentName":"Secret","addressId":1,"documentationId":1,"address":null,"documentation":null,"associationsEts":[],"prices":[]},{"establishmentId":2,"establishmentName":"HRB","addressId":2,"documentationId":2,"address":null,"documentation":null,"associationsEts":[],"prices":[]}]

My model class :

    class Establishment {
      final int id;
      final String name;
      final int addressid;
      final int documentationid;
    
      Establishment(
          {required this.id,
          required this.name,
          required this.addressid,
          required this.documentationid});
    
      factory Establishment.fromJson(Map<String, dynamic> json) {
        return Establishment(
            id: json['id'],
            name: json['name'],
            addressid: json['addressid'],
            documentationid: json['documantationid']);
      }
    }

The problem is that snapshot got an error , I would like snapshot to accept null values, could someone help me to fix this ? Thanks

CodePudding user response:

The error ocurrs in your "fromJson" parsing, replace your factory fromJson function to this:

factory Establishment.fromJson(Map<String, dynamic> json) {
        return Establishment(
            id: json['establishmentId'],
            name: json['establishmentName'],
            addressid: json['addressId'],
            documentationid: json['documentationId']);
      }

Tip: Check the camelCase name, the names must be equals in your parsing.

  •  Tags:  
  • Related