Created
June 18, 2021 16:11
-
-
Save tayormi/9a03ed4e02afddbe573d122bc28af484 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| import 'package:freezed_annotation/freezed_annotation.dart'; | |
| import 'package:hooks_riverpod/hooks_riverpod.dart'; | |
| part 'request_state_notifier.freezed.dart'; | |
| class RequestStateNotifier<T> extends StateNotifier<RequestState<T>> { | |
| RequestStateNotifier() : super(RequestState.idle()); | |
| Future<RequestState<T>> makeRequest(Future<T> Function() function) async { | |
| try { | |
| state = RequestState<T>.loading(); | |
| final response = await function(); | |
| final newState = RequestState<T>.success(response); | |
| if (mounted) { | |
| state = newState; | |
| } | |
| return newState; | |
| } catch (e, st) { | |
| final newState = RequestState<T>.error(e, st); | |
| if (mounted) { | |
| state = newState; | |
| } | |
| return newState; | |
| } | |
| } | |
| } | |
| @freezed | |
| class RequestState<T> with _$RequestState<T> { | |
| const factory RequestState.idle() = Idle<T>; | |
| const factory RequestState.loading() = Loading<T>; | |
| const factory RequestState.success(T? value) = Success<T>; | |
| const factory RequestState.error(Object error, StackTrace stackTrace) = | |
| Error<T>; | |
| } |
Author
Thank you for this!! i have actually thought of having something like this, because i keep writing StateNotifiers from scratch every time i need to make a request!!!!
You're welcome. This should save you a lot of time.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Thank you for this!! i have actually thought of having something like this, because i keep writing StateNotifiers from scratch every time i need to make a request!!!!