[Help] Handle success and error case with Riverpod. #3479
Replies: 5 comments 1 reply
-
Can anyone help me? |
Beta Was this translation helpful? Give feedback.
-
You can find information on the side effects in this article's dedicated section. |
Beta Was this translation helpful? Give feedback.
-
I think you can simplify your code a bit. From this: Future<bool> deleteUser({required String code}) async {
try {
await _userRepo.deleteUser(code);
state = const AsyncLoading();
state = await AsyncValue.guard(() => _fetchUsers());
return true;
} on Exception catch (_) {
state = const AsyncValue.error('Có lỗi khi xoá user', StackTrace.empty);
state = AsyncValue.data(state.value ?? []);
return false;
}
} To this: Future<bool> deleteUser({required String code}) async {
state = const AsyncLoading();
state = await AsyncValue.guard(() async {
await _userRepo.deleteUser(code);
await _fetchUsers());
});
} With this change, if any of the async functions fail, your state will become an Then you can use class YourWidget extends ConsumerWidget {
@override
Widget build(BuildContext context, WidgetRef ref) {
// error handling
ref.listen<AsyncValue<void>>(
userControllerProvider,
(_, state) => /* show error if `state.hasError` */,
); Here's a complete article explaining this approach in more detail: https://codewithandrea.com/articles/loading-error-states-state-notifier-async-value/ |
Beta Was this translation helpful? Give feedback.
-
Thank for your reply. But if i do that way, if an error occur, the UI will show the error not the previous list |
Beta Was this translation helpful? Give feedback.
-
@Trung15010802 you should still be able to access the previous value even when there's an error. Read this for details: https://chooyan.hashnode.dev/why-we-need-asyncvalue-of-riverpod |
Beta Was this translation helpful? Give feedback.
-
I don't know what the best practice is for showing a dialog if there's an error or success when performing a CRUD action.
Right now, I'm just returning a boolean variable to show a success or error dialog. However, I think I can do something better with Riverpod
Beta Was this translation helpful? Give feedback.
All reactions