flutter 在asyncNotifier中维护状态

6jygbczu  于 2023-04-13  发布在  Flutter
关注(0)|答案(1)|浏览(161)

我必须在Flutter应用程序中管理两个身份验证。主要的一个是使用firebase身份验证进行维护。对于另一个,我已经使用OtherUser对象创建了AsyncNotifier
这里的想法是通过所有应用程序维护当前的OtherUser
以下是我的想象:

import 'package:hooks_riverpod/hooks_riverpod.dart';

class PatientController extends AsyncNotifier<Patient?> {
  PatientController();

  bool firstBuild = true;
  static PatientController patientController = PatientController();

  @override
  Future<Patient?> build() async {
    return null;
  }

  void logInPatient({
    required String firstName,
    required String lastName,
    required DateTime birthday,
  }) async {
    
    state = const AsyncLoading();
    state = await AsyncValue.guard(() async {
      final patient = await ref.read(repositoryProvider).getPatient(
            firstName: firstName,
            lastName: lastName,
            birthday: birthday,
          );
      return patient;
    });
  }

  void createPatient(
      {required String firstName,
      required String lastName,
      required DateTime birthday,
      }) async {
    state = const AsyncLoading();
    state = await AsyncValue.guard(() async {
      final patient = await ref.read(repositoryProvider).createPatient(
            firstName: firstName,
            lastName: lastName,
            birthday: birthday,
          );
      ref.read(routerProvider).go('/doctor/patient/home');
      return patient;
    });
  }

  void updatePatient(
      {required String firstName,
      required String lastName,
      required DateTime birthday,}) {
    update((data) async {
      state = const AsyncLoading();
      final patient = data!.copyWith(
        firstName: firstName,
        lastName: lastName,
        birthday: birthday,
      );

      await ref.read(repositoryProvider).updatePatient(patient: patient);
      return patient;
    });
  }

  void logPatientOut() {
    update((data) {
      // do stuff
      return null;
    });
  }

}

final patientControllerProvider =
    AsyncNotifierProvider<PatientController, Patient?>(
        () => PatientController.patientController);

最后,它是一种单体。
它工作正常,但我不确定这是不是最佳实践,否则它总是会调用rebuild,我应该传递一个String作为id来获取id,整个应用程序都是这样。
你知道我该怎么做吗

i86rm4rw

i86rm4rw1#

为什么不这样做:

final patientControllerProvider =
    AsyncNotifierProvider<PatientController, Patient?>(PatientController.new);

您的build()方法为空并且没有依赖项。除非您决定显式调用invalidate/refresh或在整个容器上调用dispose(),否则它不会重新构建。此外,您没有应用autoDispose修饰符,因此patientControllerProvider不会被释放。

相关问题