Skip to content

Instantly share code, notes, and snippets.

@tayormi
Created June 18, 2021 16:11
Show Gist options
  • Select an option

  • Save tayormi/9a03ed4e02afddbe573d122bc28af484 to your computer and use it in GitHub Desktop.

Select an option

Save tayormi/9a03ed4e02afddbe573d122bc28af484 to your computer and use it in GitHub Desktop.
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>;
}
@WojuadeAA
Copy link

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!!!!

@tayormi
Copy link
Author

tayormi commented Jun 18, 2021

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