我正在使用提供程序侦听器获取状态值,然后在状态有错误时返回小吃栏,或者在状态完成值时导航到另一个页面。 这是我的用户界面
return ProviderListener<LoginState>(
provider: loginControllerProvider,
onChange: (BuildContext context, value) {
if (value.loginStatus == Status.COMPLETED) {
print('redirect');
}
if (value.loginStatus == Status.ERROR) {
print('error');
}
if (value.loginStatus == Status.LOADING) {
print('loading');
}
},
我的供应商
final loginControllerProvider = StateNotifierProvider.autoDispose<LoginController,
LoginState>(
(ref) => LoginController(ref.read));
我的状态通知器
class LoginController extends StateNotifier<LoginState> {
LoginController(this._read) : super(LoginState.initial());
final Reader _read;
void login(String email, String password) async {
state = state.copyWith(loginStatus: Status.LOADING, isAuthenticated: false);
final response = await _read(authRepositoryProvider).doLogin(email, password);
if (response is AppException) {
state = state.copyWith(
loginStatus: Status.ERROR,
error: response.toString(),
isAuthenticated: false);
} else {
state = state.copyWith(loginStatus: Status.COMPLETED, isAuthenticated: true);
}
}
}
我的登录状态
enum Status { INITIAL, LOADING, COMPLETED, ERROR }
class LoginState extends Equatable {
final Status loginStatus;
final String? error;
final bool isAuthenticated;
LoginState(
{required this.loginStatus, this.error, required this.isAuthenticated});
factory LoginState.initial() {
return LoginState(loginStatus: Status.INITIAL, isAuthenticated: false);
}
LoginState copyWith(
{required Status loginStatus,
String? error,
required bool isAuthenticated}) {
return LoginState(
loginStatus: loginStatus,
error: error,
isAuthenticated: isAuthenticated);
}
@override
List<Object?> get props => [loginStatus, error, isAuthenticated];
}
最后是调用登录方法的函数
onTap: () => context
.read(loginControllerProvider.notifier)
.login(emailEditingController.text,
passwordEditingController.text),
问题是即使 login 方法中的 state 实际发生了变化,onchange 方法即使有错误也只返回打印加载语句。