dart 当StateNotifierClass更改为NotifierClass时,应如何重写NotifierProvider?

wlp8pajw  于 12个月前  发布在  其他
关注(0)|答案(1)|浏览(69)

我已经将StateNotifier类更改为Notifier类,但我不知道如何重写Provider。因为我的StateNotifier类使用其他Providers观察到的值作为示例变量。如何在NotifierProvider中使用其他提供程序观察到的值?
新创建的NotifierClass

class CommunityController extends Notifier<bool> {
  final CommunityRepository _communityRepository;
  final StorageRepository _storageRepository;
  final Ref _ref;
  CommunityController({
    required CommunityRepository communityRepository,
    required StorageRepository storageRepository,
    required Ref ref,
  })  : _communityRepository = communityRepository,
        _storageRepository = storageRepository,
        _ref = ref;

  @override
  bool build() {
    return false;
  }

  void createCommunity(String name, BuildContext context) async {
    state = true;
    final uid = _ref.read(userProvider)?.uid ?? '';
    Community community = Community(
      id: name,
      name: name,
      banner: Constants.bannerDefault,
      avatar: Constants.avatarDefault,
      members: [uid],
      mods: [uid],
    );

    final res = await _communityRepository.createCommunity(community);
    state = false;
    res.fold((l) => showSnackBar(context, l.message), (r) {
      showSnackBar(context, 'Community created successfully!');
      Routemaster.of(context).pop();
    });
  }

  Stream<Community> getCommunityByName(String name) {
    return _communityRepository.getCommunityByName(name);
  }
}

StateNotifierProvider重写为NotifierProvider

final communityControllerProvider = StateNotifierProvider<CommunityController, bool>((ref) {
  final communityRepository = ref.watch(communityRepositoryProvider);
  final storageRepository = ref.watch(storageRepositoryProvider);
  return CommunityController(
    communityRepository: communityRepository,
    storageRepository: storageRepository,
    ref: ref,
  );
});
zf9nrax1

zf9nrax11#

你可以这样做:

class CommunityNotifier extends Notifier<bool> {
  late final CommunityRepository _communityRepository;
  late final StorageRepository _storageRepository;

  @override
  bool build() {
    _communityRepository = ref.watch(communityRepositoryProvider);
    _storageRepository = ref.watch(storageRepositoryProvider);
    return false;
  }

}

// using tear-off
final communityNotifier = NotifierProvider<CommunityNotifier, bool>(CommunityNotifier.new);

build方法中,您可以安全地使用ref.listenref.watch,并且您的CommunityController将具有正确的依赖项。

奖励Ref不再需要传递。我们从Notifier类继承它。

相关问题