英文:
#Flutter/Riverpod - Is it possible to call only error when using AsyncNotifier?
问题
我正在使用Riverpod作为我的Flutter项目的状态管理,并且目前正在处理身份验证服务。我有一个AuthNotifier扩展AsyncNotifier的问题是当我像这样调用AuthService时:
Future<void> logout() async {
state = const AsyncValue.loading();
state = await AsyncValue.guard(() async {
return await authService.logout();
});
state.when(
data: (data){},
error: (error, stackTrace){
ref.read(errorProvider.notifier).createException(exception: error.toString(), errorTitle: "Logout Error");
},
loading: (){},
);
}
我只在state.when中使用了error,但我也有这段未使用的代码。
我尝试查看state或state.when的方法,但无法找到任何东西,可能是因为答案不在那里,或者是因为我没有看到它。如果有人对在Notifier内部处理错误有其他建议,我愿意听取建议。
英文:
I am using riverpod as state management for my flutter project and am currently working on auth services. I am having AuthNotifier extending AsyncNotifier. The problem is when i make a call to the AuthService for example like that:
Future<void> logout() async {
state = const AsyncValue.loading();
state = await AsyncValue.guard(() async {
return await authService.logout();
});
state.when(
data: (data){},
error: (error, stackTrace){
ref.read(errorProvider.notifier).createException(exception: error.toString(), errorTitle: "Logout Error");
},
loading: (){},
);
}
I am only using the error in the state.when but i also have this unused code.
I tried looking for at the methods of state or state.when but couldn't find anything either because the answer is not there or because i didn't see it. If anyone has alternative on handling the error inside the Notifier i am open to suggestions.
答案1
得分: 1
使用whenOrNull
/mapOrNull
或maybeWhen
/maybeMap
来处理部分状态,例如:
final Object? newState = state.whenOrNull(
error: (error, stackTrace){
...
},
);
// 或者
final Object newState = state.whenOrNull(
orElse: () => ...,
error: (error, stackTrace){
...
},
);
英文:
Use whenOrNull
/mapOrNull
or maybeWhen
/maybeMap
to handle only some states, for example:
final Object? newState = state.whenOrNull(
error: (error, stackTrace){
...
},
);
// or
final Object newState = state.whenOrNull(
orElse: () => ...,
error: (error, stackTrace){
...
},
);
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论