我有一个冻结的类,不知何故我无法访问copyWith方法。我错在哪里?
类:
@freezed
class LoginState with _$LoginState {
const factory LoginState({
String? username,
String? password,
@Default(false) bool isValid,
String? errorMessage,
}) = _LoginState;
factory LoginState.empty() => LoginState();
factory LoginState.initial() = _Initial;
}
尝试像这样访问copyWith:
LoginState state = LoginState();
state.copyWith(); //cannot access copyWith
copyWith
仅为在其构造函数中具有参数的类生成。在您的示例中,_LoginState
是唯一具有参数的:so:
LoginState state1 = _LoginState();
state1.copyWith(); //works!
LoginState state2 = _Initial();
state2.copyWith(); //Doesn't exist on this class
(state3 as _LoginState).copyWith(); //works!
所以要么做这个类型转换,以确保你正在使用一个有参数的类,或者给_Initial
添加一个参数,给它一个copyWith方法,实际做一些事情。