Flutter - 卡住包 - 如何正确组合类

标签 flutter dart composition

我很难理解如何将包用于基本情况,例如描述 API 请求/响应。我可能会陷入一个循环,在这个循环中我已经有了一些想法,并且我正试图不惜一切代价让它以这种方式工作,但我看不到更简单的解决方案。

例子:

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

然后

@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);
}

那里有些东西很臭,我确定我遗漏了一些东西,而且我无法正确组合这些类。 在这种情况下,卡住甚至可能是矫枉过正?

最佳答案

您不能实现/扩展卡住类。

将您的 BaseResponse/BaseRequest 更改为:

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

abstract class BaseResponse{
  bool get c;
}

或者使用组合而不是继承:

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

关于Flutter - 卡住包 - 如何正确组合类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63779359/

相关文章:

Flutter 不同的创建状态方式有什么区别?

dart - 聚合物 1.0 中的绑定(bind)属性和特性

dart - 是否有事件导致鼠标中键下降?

firebase - 在Dart中从Cloud_Firestore获取 bool 状态

Haskell Monad 绑定(bind)运算符混淆

flutter - 如何在 flutter 中使用路由导航到主页面以外的页面?

flutter - 如何在布局中扩展嵌套容器?

Flutter BLOC 状态更新但始终为空值

c++ - 必要时违反继承之上的组合可以吗?

Python 对象组合 - 从调用它的类中访问方法