0

I have data which I receive from the server. I get through the model in which there is a froJson, toJson method. In the toJson method, I had a problem. When I want to convert the data back to Json, I get an error (I attached a screenshot below). Tell me how can I solve this problem so that everything is fine with the data and I can convert them to Json?

mainModel

class MainModel {
  String name;
  List<AmenitiesModel>? amenities;
  List<DeviceModel>? devices;
  List<PhotoModel>? photos;

  MainModel ({
    required this.name,
    this.amenities,
    this.devices,
    this.photos,
  });

  factory MainModel .fromJson(Map<String, dynamic> json) =>
      MainModel(
          id: json['id'],
          name: json['name'],
          amenities: json['amenities'] != null
              ? List<AmenitiesModel>.from(
                  json['amenities'].map(
                    (item) => AmenitiesModel.fromJson(item),
                  ),
                ).toList()
              : null,
          user: json['user'] != null ? User.fromJson(json['user']) : null,
          devices: json['devices'] != null
              ? List<PublicChargingDeviceModel>.from(
                  json['devices'].map(
                    (item) => DeviceModel.fromJson(item),
                  ),
                ).toList()
              : null,
          photos: json['gallery'] != null
              ? List<PhotoModel>.from(
                  json['gallery'].map(
                    (item) => PhotoModel.fromJson(item),
                  ),
                ).toList()
              : null);

  Map<String, dynamic> toJson() {
    return {
      'name': name,
      'amenities': amenities!.map((e) => e.toJson()).toList(),
      'devices': devices?.map((e) => e.toJson()).toList(),
      'gallery': photos?.map((e) => e.toJson()).toList(),
    };
  }

amenitiesModel

class AmenitiesModel {
  String name;
  final String type;

  AmenitiesModel({required this.type, required this.name});

  factory AmenitiesModel.fromJson(Map<String, dynamic> json) {
    return AmenitiesModel(
      type: json['type'],
      name: json['name'],
    );
  }

  Map<String, dynamic> toJson() {
    return {
      if (type == 'other') 'name': name,
      'type': type,
    };
  }

1 Answer 1

1

Reading map can return null, you can provide default value on null case like

factory AmenitiesModel.fromJson(Map<String, dynamic> json) {
  return AmenitiesModel(
    type: json['type']??"",
    name: json['name']??"",
  );
}

Sign up to request clarification or add additional context in comments.

1 Comment

either that or declare "type" and "name" in AmenitiesModel as nullable strings

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.