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 ?

2 Answers 2

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');

    }
}

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

1 Comment

I'll try this way .. Thanks <3
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

Comments

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.