简体   繁体   中英

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.

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();
          },
        ),
      ),
    );
  }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM