我已经将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,
);
});
1条答案
按热度按时间zf9nrax11#
你可以这样做:
在
build
方法中,您可以安全地使用ref.listen
和ref.watch
,并且您的CommunityController
将具有正确的依赖项。奖励:
Ref
不再需要传递。我们从Notifier
类继承它。