Flutter: Not able to use nested models with Entities. (Entities, Models, Equatable, Flutter, Dart, json_serializable,Json Serialization)

Viewed 94

I have two file for a single data i.e Entity and Model. To separate the entire logic from each other and to follow best practices. Whenever I am trying to use nested Entities and parsing through @JsonSerializable it's showing me error.

Note: I have tried @JsonConverter too. It's not working.

I'm sure I'm missing something over there but can't get it. Please help.

test_entity.dart

class TestEntity extends Equatable {
final String id;
final List<AddressEntity> address;

const TestEntity({
required this.id,
required this.address,
});
@override
List<Object?> get props => [
    id,
    address,
  ];
}

test_model.dart

part 'test_model.g.dart';

@JsonSerializable(explicitToJson: true)
class TestModel extends TestEntity {
const TestModel({
required String id,
required List<AddressModel> address,
}) : super(
      id: id,
      address: address,
    );
factory TestModel.fromJson(Map<String, dynamic> json) =>
  _$TestModelFromJson(json);

Map<String, dynamic> toJson() => _$TestModelToJson(this);
}

address_entity.dart

class AddressEntity extends Equatable {
 final String id;
 final String title;

const AddressEntity({
 required this.id,
 required this.title,
});
@override
List<Object?> get props => [
    id,
    title,
  ];
}

address_model.dart

part 'address_model.g.dart';

@JsonSerializable()
class AddressModel {
 final String id;
 final String title;

 AddressModel({
  required this.id,
  required this.title,
 });

 factory AddressModel.fromJson(Map<String, dynamic> json) =>
    _$AddressModelFromJson(json);

 Map<String, dynamic> toJson() => _$AddressModelToJson(this);
 }

When I use AddressModel instead AddressEntity

Here is the Snap of Code

Also This Code:

1 Answers

Any property of a JsonSerializeble class should have its own fromJson() constructor. Your TestEntity class has the List<AddressEntity> as a property, but AddressEntity has no such constructor.

To fix this, just implement fromJson() constructor and toJson() method for the AddressEntity class. There is no difference if you make it by hand or with the help of the JsonSerializeble generator.

Related