[英]StateNotifierProvider not persisting state in Flutter (Riverpod)
[英]Flutter riverpod, StateNotifierProvider initialise StateNotifier best practice
我想异步初始化我的 StateNotifier。
我想我可以做到,我只是想检查一下我正在做的是最佳实践。
这有点伪,但希望是有道理的......
final signInProvider = StateNotifierProvider<ExampleNotifier, SignInState>((ref) {
return ExampleNotifier();
});
class ExampleNotifier extends StateNotifier<SignInState> {
//emits loading state to start with
ExampleNotifier() : super(Loading()) {
//We then invoke a function that gets some data... from an api
getAsyncDate();
}
void getAsyncDate() async {
final foo = await someAsyncCall();
//once its returned we set the state to it...
state = foo;
}
}
基本上可以使用构造函数调用 function 然后在 StateNotifier 上设置 state 吗?
谢谢
是的,这是很好的练习。 新版本的 Riverpod 2.0 有一个 class AsyncNotifier<State>
(就像StateNotifier<State>
):
import 'dart:async';
import 'package:flutter_riverpod/flutter_riverpod.dart';
class SignInNotifier extends AsyncNotifier<void> {
// Override the [build] method to return a [FutureOr]
@override
FutureOr<void> build() {
// Return a value (or do nothing if the return type is void)
}
Future<void> signIn() async {
// Read the repository using ref
final authRepository = ref.read(authRepositoryProvider);
// Set the loading state
state = const AsyncLoading();
// Sign in and update the state (data or error)
state = await AsyncValue.guard(authRepository.signIn);
}
}
这个 class 的提供者看起来像这样:
// Using a constructor tear-off:
final signInProvider = AsyncNotifierProvider<SignInNotifier, void>(SignInNotifier.new)
请注意创建提供程序的 function 如何没有ref
参数。
但是, ref
始终可以作为Notifier
或AsyncNotifier
子类中的属性进行访问,从而可以轻松读取其他提供程序。
更多信息:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.