I am using cubit
for state management. And i have a variable in the state. And it gets resetted when some other state
is emitted.
state_file
class UserState extends Equatable {
final SampleModel? sampleModel;
const UserState({this.sampleModel});
UserState copyWith({String? name, String? avatar}) {
return UserState(
sampleModel: SampleModel(
name: name ?? sampleModel?.name ?? "",
avatar: avatar ?? sampleModel?.avatar ?? ""));
}
@override
List<Object?> get props => [sampleModel];
}
class UserMainLoadingState extends UserState {} // this resets my sampleModel why ?
class UserSavedUpdatedState extends UserState { // One way around is by sending props in every state
UserSavedUpdatedState({required SampleModel sample})
: super(sampleModel: sample);
}
cubit_file
Future<void> addSampleUser({required SampleModel sample}) async {
print("I am inside this add sample");
print("State is ${state.sampleModel!}"); // prints sampleModel
emit(UserSideLoadingState());
print("State is ${state.sampleModel!}"); // Null check operator used on a null value
}
Why this happens, and how to overcome this without passing props to every state.
It's resetting because when you emit UserMainLoadingState
you are not copying SampleModel
from the previous state, so it's lost. Simple solution would be:
class UserMainLoadingState extends UserState {
const UserMainLoadingState({required SampleModel sample})
: super(sampleModel: sample);
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.