我有一个应用程序,我正在使用 riverpod 管理状态。好吧,我注意到在页面导航上我丢失了状态并重置为初始状态。这是我的代码;
提供者
final registerAuthControllerProvider = StateNotifierProvider.autoDispose<
RegisterAuthController,
AuthenticatingUser>((ref) => RegisterAuthController(ref.read));
状态通知代码
class RegisterAuthController extends StateNotifier<AuthenticatingUser> {
RegisterAuthController(this._read) : super(AuthenticatingUser.initial());
final Reader _read;
void updateEmail(String email) async {
state = state.copyWith(authenticating: true);
final getEmail = await _read(authRepositoryProvider).checkEmail(email);
if (getEmail == 'Email Already Exists') {
state = state.copyWith(authenticating: false, emailError: true);
}
state = state.copyWith(authenticating: false, email: email);
print(state);
}
void updatePersonalDetails(
String firstName, String lastName, String phoneNumber) {
state = state.copyWith(
authenticating: false,
firstName: firstName,
lastName: lastName,
phoneNumber: phoneNumber);
print(state);
} }
状态类 导入 'package:equatable/equatable.dart';
class AuthenticatingUser extends Equatable {
final String? firstName;
final String? lastName;
final String? email;
final String? phoneNumber;
final String? password;
final int? passcode;
final String? img;
final bool authenticating;
final bool emailError;
AuthenticatingUser(
{this.firstName,
this.lastName,
this.email,
this.phoneNumber,
this.password,
this.passcode,
required this.authenticating,
required this.emailError,
this.img});
factory AuthenticatingUser.initial() {
return AuthenticatingUser(
firstName: null,
lastName: null,
email: null,
phoneNumber: null,
passcode: null,
password: null,
authenticating: false,
emailError: false,
img: null);
}
AuthenticatingUser copyWith(
{String? firstName,
String? lastName,
String? email,
String? phoneNumber,
int? passcode,
required bool authenticating,
bool emailError = false,
String? password,
String? img}) {
return AuthenticatingUser(
authenticating: authenticating,
firstName: firstName,
lastName: lastName,
email: email,
password: password,
passcode: passcode,
phoneNumber: phoneNumber,
emailError: emailError,
img: img);
}
@override
List<Object?> get props =>
[firstName, lastName, email, phoneNumber, password, img, authenticating];
}
第 1 页点击方法
onTap: () => {
print('object'),
if (EmailValidator.validate(emailEditingController.text))
{
context
.read(registerAuthControllerProvider.notifier)
.updateEmail(emailEditingController.text),
},
// notValid = true,
},
更新电子邮件函数的打印状态返回带有更新电子邮件的状态,但是当通过提供程序侦听器导航到第二页时,我使用 updatePersonalDetails 函数更新状态时,我看到 authenticateduser.email 状态值返回到无效的。就像在每次页面导航后都会重置状态。我希望状态在页面导航后保持不变。我怎样才能做到这一点?