我想异步初始化我的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;
}
}
基本上可以使用构造函数调用一个函数,然后在StateNotifier上设置状态吗?
谢谢
1条答案
按热度按时间44u64gxh1#
是的,这是一个很好的练习。新版本的Riverpod 2.0有一个类
AsyncNotifier<State>
(就像StateNotifier<State>
一样):此类的提供程序如下所示:
请注意,创建提供程序的函数没有
ref
参数。但是,
ref
始终可以作为Notifier
或AsyncNotifier
子类中的属性进行访问,这使得其他提供程序易于读取。更多信息:
异步通知程序如何工作
AsyncNotifier-class