简体   繁体   English

Riverpod:您如何使用 StateNotifier 管理加载和错误状态?

[英]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?如何使用 StateNotifier 的加载/错误状态,就像我们在 Riverpod 中使用 FutureProvider 一样?

We can do the same with Provider using setState, var isLoading with ternary operator and didChangeDependencies.我们可以使用 setState 对 Provider 执行相同的操作,使用三元运算符和 didChangeDependencies 进行 var isLoading。

FutureProvider works with AsyncValue . FutureProviderAsyncValue一起使用。
You can use AsyncValue with a StateNotifier too like so:您也可以将AsyncValueStateNotifier一起使用,如下所示:

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:它允许您像这样使用when方法:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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