Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Riverpod: How do you manage loading and error states with StateNotifier?

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.

like image 940
Anmol Singh Avatar asked Oct 26 '25 12:10

Anmol Singh


1 Answers

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();
          },
        ),
      ),
    );
  }
}
like image 185
Josteve Avatar answered Oct 29 '25 02:10

Josteve



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!