Skip to content

Instantly share code, notes, and snippets.

@rutvik110
Created December 17, 2021 10:23
Show Gist options
  • Save rutvik110/9d63161feac1bd5b62bf08543810e6d7 to your computer and use it in GitHub Desktop.
Save rutvik110/9d63161feac1bd5b62bf08543810e6d7 to your computer and use it in GitHub Desktop.
FutureState Notifier Riverpod
import 'package:flutter_riverpod/flutter_riverpod.dart';
//a state notifier that can be used to call a future after an event.
//it will automatically update the state when the future completes
//call [doRequest] to call the future
//pass in [request] to the [doRequest] function or in the constructor
//the [request] in the doRequest function will take precendence over the [request] in the constructor
class FutureStateNotifier<T> extends StateNotifier<AsyncValue<T>> {
FutureStateNotifier({this.request}) : super(AsyncValue<T>.loading());
final Future<T> Function()? request;
Future<void> doRequest({Future<T> Function()? request}) async {
// try {
state = AsyncValue.loading();
state = await AsyncValue.guard(() async {
late T data;
if (request != null) {
data = await request();
} else if (this.request != null) {
data = await this.request!();
} else {
throw ArgumentError("Request not found for future state notifier");
}
// if (mounted) return data;
return data;
});
}
// on ApiCallException catch (e) {
// state = AsyncValue.error(e);
// } catch (e) {
// state = AsyncValue.error(e);
// }
// }
}
final exampleFutureStateProvider =
StateNotifierProvider<FutureStateNotifier<void>, AsyncValue<void>>((ref) {
return FutureStateNotifier();
});
// ref.listen<AsyncValue<void>>(checkForUpdateStateNotifier,
// (previousState, newState) {
// newState.when(
// loading: () {},
// data: (data) async {
// Do Something...
// },
// error: (e, s) {
// log(e.toString());
// },
// );
// });
// ref.read(checkForUpdateStateNotifier.notifier).doRequest(
// request: () {}
// );
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment