the argument type 'Zone?' can't be assigned to the parameter type 'Zone' in flutter

Issue

How to solve the below error in a flutter?

I create the Data class to read the JSON object in a flutter. the Data class was working fine but I got the argument type ‘Zone?’ can’t be assigned to the parameter type ‘Zone’ in a flutter error…
What can I do?

MY Code

class DatumDatum {
    DatumDatum({
        required this.vehicleCc,
        required this.zone,
        required this.value,
    });

    final String vehicleCc;
    final Zone zone;
    final double value;

    factory DatumDatum.fromJson(Map<String, dynamic> json) => DatumDatum(
        vehicleCc: json["vehicleCC"],
        zone: zoneValues.map[json["zone"]], // tis line I got a error
        value: json["value"].toDouble(),
    );

    Map<String, dynamic> toJson() => {
        "vehicleCC": vehicleCc,
        "zone": zoneValues.reverse[zone],
        "value": value,
    };
}

enum Zone { ZONE_A, ZONE_B }

final zoneValues = EnumValues({
    "Zone A": Zone.ZONE_A,
    "Zone B": Zone.ZONE_B
});

class EnumValues<T> {
    late Map<String, T> map;
    late Map<T, String> reverseMap;

    EnumValues(this.map);

    Map<T, String> get reverse {
        if (reverseMap == null) {
            reverseMap = map.map((k, v) => new MapEntry(v, k));
        }
        return reverseMap;
    }
}

Solution

Here the problem is you are using a null-safety version of flutter because of that we need to handle nulls values.

Here is the solution:

As you data received from API service the received value might be null which means mapping of the field will return null as well and in your model field you have declared variable as it can’t be null, so the solution would be if you know that the API value always contains field than in json you can add null check operator like

  factory DatumDatum.fromJson(Map<String, dynamic> json) => DatumDatum(
        vehicleCc: json["vehicleCC"],
        zone: zoneValues.map[json["zone"]]!, // ! this is null check operator
        value: json["value"].toDouble(),
      );

or if API may contain NULL value for json["zone"] parameter you can declare variable as final Zone? zone;

Answered By – Parth Virani

Answer Checked By – Willingham (FlutterFixes Volunteer)

Leave a Reply

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