Flutter riverpod、StateNotifierProvider初始化状态通知程序最佳实践

jjjwad0x  于 2022-12-05  发布在  Flutter
关注(0)|答案(1)|浏览(214)

我想异步初始化我的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上设置状态吗?
谢谢

44u64gxh

44u64gxh1#

是的,这是一个很好的练习。新版本的Riverpod 2.0有一个类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);
  }
}

此类的提供程序如下所示:

// Using a constructor tear-off:
final signInProvider = AsyncNotifierProvider<SignInNotifier, void>(SignInNotifier.new)

请注意,创建提供程序的函数没有ref参数。
但是,ref始终可以作为NotifierAsyncNotifier子类中的属性进行访问,这使得其他提供程序易于读取。

更多信息:

异步通知程序如何工作
AsyncNotifier-class

相关问题