How to use loading/error states with StateNotifier
like we do with FutureProvider
in Riverpod
?
We can do the same with Provider using setState, var isLoading with ternary operator and didChangeDependencies.
How to use loading/error states with StateNotifier
like we do with FutureProvider
in Riverpod
?
We can do the same with Provider using setState, var isLoading with ternary operator and didChangeDependencies.
FutureProvider
works with AsyncValue
.
You can use AsyncValue
with a StateNotifier
too like so:
final randomNumberProvider = StateNotifierProvider<RandomNumberNotifier, AsyncValue<int>>((ref) {
return RandomNumberNotifier();
});
class RandomNumberNotifier extends StateNotifier<AsyncValue<int>> {
RandomNumberNotifier() : super(const AsyncLoading());
void getNewNumber() async {
state = const AsyncLoading();
await Future.delayed(const Duration(seconds: 3));
final number = Random().nextInt(500);
state = AsyncValue.data(number);
}
}
And it allows you to use the when
method like so:
class Page extends ConsumerWidget {
const Page({Key? key}) : super(key: key);
@override
Widget build(BuildContext context, WidgetRef ref) {
final randomNumberNotifier = ref.watch(randomNumberProvider);
return Scaffold(
floatingActionButton: FloatingActionButton(
onPressed: () {
final p = ref.read(randomNumberProvider.notifier);
p.getNewNumber();
},
child: const Icon(Icons.add),
),
body: Center(
child: randomNumberNotifier.when(
data: (data) {
return Text(data.toString());
},
error: (_, __) {
return const Text("An error occurred");
},
loading: () {
return const CircularProgressIndicator();
},
),
),
);
}
}