0

I have this class

@freezed
abstract class CartEntity with _$CartEntity {
  const factory CartEntity.empty(String status, String message) = _Empty;

  const factory CartEntity.notEmpty(int x) = _NotEmpty;

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

}

And this converter

class CartEntityConverter
    implements JsonConverter<CartEntity, Map<String, dynamic>> {
  const CartEntityConverter();

  @override
  CartEntity fromJson(Map<String, dynamic> json) {
    //the problem here
    print(json);// null 

    return _Empty.fromJson(json);

  }

  @override
  Map<String, dynamic> toJson(CartEntity object) {
    return object.toJson();
  }
}

And this wrapper class

@freezed
abstract class CartEntityWrapper with _$CartEntityWrapper {
  const factory CartEntityWrapper(@CartEntityConverter() CartEntity cartEntity) =
      CartEntityWrapperData;

  factory CartEntityWrapper.fromJson(Map<String, dynamic> json) =>
      _$CartEntityWrapperFromJson(json);
}

And iam called

    final cartEntity = CartEntityWrapperData.fromJson({'x':'y'});
    print(cartEntity);

fromJson method which in CartEntityConverter is always receive null json so what's i made wrong ?

Mohamed Gaber
  • 1,625
  • 1
  • 10
  • 22

2 Answers2

1

Instead of making yet another converter class that you use directly, you could just add .fromJsonA method in the main class.

It will looks like this one:

@freezed
abstract class CartEntity with _$CartEntity {
  const factory CartEntity.empty(String status, String message) = _Empty;

  const factory CartEntity.notEmpty(int x) = _NotEmpty;

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

  factory CartEntity.fromJsonA(Map<String, dynamic> json) {

if (/*condition for .empty constructor*/) {
      return _Empty.fromJson(json);
    } else if (/*condition for .notEmpty constructor*/) {
      return _NotEmpty.fromJson(json);
    } else {
      throw Exception('Could not determine the constructor for mapping from JSON');

    }
}

}
Nikola Simonov
  • 401
  • 3
  • 7
0

solved by using

    final cartEntity = CartEntityConverter().fromJson({'x':'y'});
    print(cartEntity);

instead of

    final cartEntity = CartEntityWrapperData.fromJson({'x':'y'});
    print(cartEntity);

documentation have a lack at this point i tried random stuffs to make it work

Mohamed Gaber
  • 1,625
  • 1
  • 10
  • 22