【发布时间】:2021-11-16 10:41:24
【问题描述】:
我是 Flutter 新手,需要一些帮助 我有这个带有 GoogleMaps 的屏幕(此处为简化版):
class OrderDetailsScreen1 extends StatefulWidget {
const OrderDetailsScreen1({
Key? key,
}) : super(key: key);
@override
_OrderDetailsScreen1State createState() => _OrderDetailsScreen1State();
}
class _OrderDetailsScreen1State extends State<OrderDetailsScreen1> {
@override
Widget build(BuildContext context) {
final googleMapsNotifier =
Provider.of<GoogleMapsNotifier>(context, listen: true);
double latitude = -33.75;
double longitude = -70.67;
if (googleMapsNotifier.currentLocation != null) {
latitude = googleMapsNotifier.currentLocation!.latitude;
longitude = googleMapsNotifier.currentLocation!.longitude;
}
return Scaffold(
body: SafeArea(
child: SizedBox(
height: 300,
child: GoogleMap(
myLocationEnabled: true,
initialCameraPosition: CameraPosition(
target: LatLng(latitude, longitude),
zoom: 14,
),
),
),
),
);
}
}
我像这样从上一个屏幕推送这个屏幕
onTap: () {
Navigator.push(
context,
MaterialPageRoute(
builder: (_) => Provider<GoogleMapsNotifier>(
create: (_) => GoogleMapsNotifier(),
child: OrderDetailsScreen1(
),
)));
},
我有这样的课程GoogleMapsNotifier with ChangeNotifier
class GoogleMapsNotifier with ChangeNotifier {
final geolocatorService = GeolocatorService();
Position? currentLocation;
GoogleMapsNotifier() {
setCurrentLocation();
}
setCurrentLocation() async {
currentLocation = await geolocatorService.determinePosition();
print(currentLocation!.latitude);
notifyListeners();
}
}
在GoogleMapsNotifier 的setCurrentLocation() 内部,currentLocation 很好,并且打印得很好。但是notifyListeners() 不会将数据传回 UI (OrderDetailsScreen1)。它没有反应,我在控制台中没有错误。哪里错了?
UPD:我尝试将 MaterialPageRoute 更改为以下内容,但没有帮助
onTap: () {
Navigator.push(
context,
MaterialPageRoute(
builder: (_) => Provider.value(
value: Provider.of<GoogleMapsNotifier>(context),
child: OrderDetailsScreen1(),
)));
},
【问题讨论】:
标签: flutter flutter-provider flutter-change-notifier