gen*_*ser 0 flutter freezed flutter-freezed
我正在使用冻结的包来生成数据类。
该包支持使用注释禁用 copyWith 生成@Freezed(copyWith: false)。
我想对我的冻结数据类实现自定义copyWith。这是我的代码:
@Freezed(copyWith: false)
class AuthenticationState with _$AuthenticationState {
const factory AuthenticationState({
String? userId,
ErrorObject? errorObject,
}) = _AuthenticationState;
AuthenticationState copyWith({
String? userId,
ErrorObject? errorObject,
}) {
return AuthenticationState(
userId: userId ?? this.userId,
errorObject: errorObject, // resets if not provided
);
}
}
Run Code Online (Sandbox Code Playgroud)
I 代运行成功并且没有静态分析错误。
但是当我运行该应用程序时,我收到此错误:
authentication_bloc.freezed.dart:32:7:错误:非抽象类“_$_AuthenticationState”缺少这些成员的实现:
- AuthenticationState.copyWith 尝试任一
- 提供一个实现,
- 从超类或 mixin 继承实现,
- 将类标记为抽象类,或者
- 提供“noSuchMethod”实现。
类 __$_AuthenticationState 实现 _AuthenticationState { ^^^^^^^^^^^^^^^^^^^^^^lib/authentication/bloc/authentication_state.dart:28:23:上下文:'AuthenticationState.copyWith'在这里定义。
问题是什么?如何copyWith在冻结类中实现自定义?
如果您要向冻结模型添加方法(如本例所示),则必须定义一个私有构造函数。
因此,添加下面的行,重新生成,一切都应该正常:
const AuthenticationState._();
Run Code Online (Sandbox Code Playgroud)
IE:
@Freezed(copyWith: false)
class AuthenticationState with _$AuthenticationState {
const AuthenticationState._(); // ADD THIS LINE
const factory AuthenticationState({
String? userId,
ErrorObject? errorObject,
}) = _AuthenticationState;
...
}
Run Code Online (Sandbox Code Playgroud)
这是冷冻包装提出的要求。请参阅官方文档。
| 归档时间: |
|
| 查看次数: |
2513 次 |
| 最近记录: |