'Cannot access copyWith method on freezed class
I have a freezed class and somehow I cannot access copyWith method. What is my mistake?
Class:
@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;
}
Try to access copyWith like this:
LoginState state = LoginState();
state.copyWith(); //cannot access copyWith
Solution 1:[1]
copyWith
is only generated for classes that have parameters in their constructors. In your case, _LoginState
is the only one with parameters: so:
LoginState state1 = _LoginState();
state1.copyWith(); //works!
LoginState state2 = _Initial();
state2.copyWith(); //Doesn't exist on this class
(state3 as _LoginState).copyWith(); //works!
So either do this type casting to make sure you're working with a class that has parameters, or add a parameter to _Initial
to give it a copyWith method that actually does something.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Tony Downey |