Giovanni Londero
Giovanni Londero

Reputation: 1409

Flutter - Freezed package - How to properly compose classes

I'm having a hard time understanding how to use the package for base cases like describing API requests/responses. I might be stuck in a loop where I've got something in mind and I'm trying to make it work at all costs that way, and I can't see simpler solutions.

Example:

@freezed
abstract class BaseRequest with _$BaseRequest {
  const factory BaseRequest({
    @required int a,
    @required String b,
  }) = _BaseRequest;
}

@freezed
abstract class BaseResponse with _$BaseResponse {
  const factory BaseResponse({
    @required bool c,
  }) = _BaseResponse;
}

then

@freezed
abstract class Authentication with _$Authentication {
  @Implements(BaseRequest)
  const factory Authentication.request({
    @required int a,
    @required String b,
    @required String psw,
  }) = _AuthenticationRequest;

  @Implements(BaseResponse)
  const factory Authentication.response({
    @required bool c,
    @required String token,
  }) = _AuthenticationResponse;

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

There's something smelly there and I'm sure I'm missing something and I'm not able to properly compose those classes. Might Freezed even be overkill in this case?

Upvotes: 2

Views: 2795

Answers (1)

R&#233;mi Rousselet
R&#233;mi Rousselet

Reputation: 277747

You cannot implement/extend Freezed classes.

Either change your BaseResponse/BaseRequest to:

abstract class BaseRequest {
  int get a;
  String get b;
}

abstract class BaseResponse{
  bool get c;
}

or use composition instead of inheritance:

@freezed
abstract class Authentication with _$Authentication {
  const factory Authentication.request({
    @required BaseRequest request,
    @required String psw,
  }) = _AuthenticationRequest;

  const factory Authentication.response({
    @required BaseResponse response,
    @required String token,
  }) = _AuthenticationResponse;
}

Upvotes: 8

Related Questions