Max
Max

Reputation: 1301

Problem converting data to json "type 'Null' is not a subtype of type 'String'" in Flutter

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,
    };
  }

Upvotes: 0

Views: 76

Answers (1)

Md. Yeasin Sheikh
Md. Yeasin Sheikh

Reputation: 63569

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']??"",
  );
}

Upvotes: 1

Related Questions