我构建了一个应用程序,用户可以在其中选择他的位置,我们将显示附近的可用项目。
class LocationState { LatLng? location;
LocationState({this.location});
LocationState copyWith({LatLng? location}) =>
LocationState(location: location); }
class CurrentLocationNotifier extends StateNotifier<LocationState> {
CurrentLocationNotifier(LocationState state) : super(state);
void changeLocation(LatLng? location) {
print("new location state");
print(location);
state = state.copyWith(location: location); } }
final currentLocationProvider =
StateNotifierProvider<CurrentLocationNotifier, LocationState?>((ref) { return
CurrentLocationNotifier(LocationState()); });
当我选择新地址时,将调用通知程序内的打印:
... return AppCard(
onTap: () {
userVM.selectDefaultAddress(address: address);
locationNotifier.changeLocation(address.location);
}, ...
在页面内部,我想监听位置更改,以便我可以再次获取数据,但不会触发:
import 'package:hooks_riverpod/hooks_riverpod.dart';
class UserHomePage extends ConsumerWidget {
const UserHomePage({Key? key}) : super(key: key);
@override
Widget build(BuildContext context, WidgetRef ref) {
final homeState = ref.watch(homeVMProvider);
final userState = ref.watch(userVMProvider);
final homeVM = ref.read(homeVMProvider.notifier);
ref.listen<LocationState?>(currentLocationProvider, (previous, current) {
print("not getting called");
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(content: Text('Location changed $current')),
);
homeVM.init();
});
我已经检查过这个帖子:ref.listen 在 Riverpod flutter 中,Rémi 在那里提供了帮助,但它似乎对我不起作用
我在用:
Riverpod:^2.0.0-dev.9
hooks_riverpod:^2.0.0-dev.9
这个演示有效:https://github.com/aspiiire/riverpod-ref.listen-part8/blob/main/lib/main.dart
那么问题可能出在新版本上吗?