[英]Flutter riverpod, StateNotifierProvider initialise StateNotifier best practice
I want to initialise a my StateNotifier asynchronously.我想异步初始化我的 StateNotifier。
I think I can do it, I just want to check what I am doing is best practice.我想我可以做到,我只是想检查一下我正在做的是最佳实践。
This is a bit pseudo but hopefully makes sense...这有点伪,但希望是有道理的......
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;
}
}
Basically is it ok to use the constructor invoke a function that will then set the state on the StateNotifier?基本上可以使用构造函数调用 function 然后在 StateNotifier 上设置 state 吗?
Thanks谢谢
Yes, it's great practice.是的,这是很好的练习。 The new version of Riverpod 2.0 has a class
AsyncNotifier<State>
(like as 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);
}
}
The provider for this class looks like this:这个 class 的提供者看起来像这样:
// Using a constructor tear-off:
final signInProvider = AsyncNotifierProvider<SignInNotifier, void>(SignInNotifier.new)
Note how the function that creates the provider doesn't have a ref
argument.请注意创建提供程序的 function 如何没有
ref
参数。
However, ref
is always accessible as a property inside Notifier
or AsyncNotifier
subclasses, making it easy to read other providers.但是,
ref
始终可以作为Notifier
或AsyncNotifier
子类中的属性进行访问,从而可以轻松读取其他提供程序。
More info:更多信息:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.