ChangeNotifier更新后如何更新Google Map地图中心?
解决方案
要实现位置更新时同步移动地图中心,你可以利用Consumer2的重建时机,在位置变化时通过GoogleMapController调用相机更新方法,具体实现如下:
在Consumer2的builder方法中,获取到最新位置后,判断地图控制器是否已初始化完成,若就绪则调用相机更新方法移动地图中心。
修改后的完整代码:
class HotspotsMap extends StatelessWidget { final Completer<GoogleMapController> _controller = Completer<GoogleMapController>(); final LocationNotifier locationNotifier; HotspotsMap({Key? key, required this.locationNotifier}) : super(key: key); @override Widget build(BuildContext context) { return ChangeNotifierProxyProvider<LocationNotifier, HotspotNotifier>( create: (BuildContext context) { return HotspotNotifier(); }, update: (_, location, hotspotNotifier) => hotspotNotifier!..updateList(location.get()), child: Scaffold( appBar: AppBar( title: Text("Nearby Hotspots"), actions: <Widget>[ set_location_icon, ], ), body: Center( child: Consumer2<HotspotNotifier, LocationNotifier>( builder: (context, notifier, location, child) { var _list = notifier.list; var position = location.get(); if (position == null) { return Text("I don't know where you are"); } // 位置更新时同步移动地图中心 if (_controller.isCompleted) { _controller.future.then((controller) { controller.animateCamera( CameraUpdate.newCameraPosition( CameraPosition( target: position, zoom: 9, ), ), ); }); } Set<Marker> markers = {}; _list.forEach((spot) { var newMarker = Marker( position: LatLng(spot.latitude, spot.longitude), markerId: MarkerId(spot.locId) ); markers.add(newMarker); }); return GoogleMap( mapType: MapType.normal, markers: markers, initialCameraPosition: CameraPosition( target: position, zoom: 9, ), onMapCreated: (GoogleMapController controller) { _controller.complete(controller); }, ); }, ), ), ), ); } }
关键说明
_controller.isCompleted用于判断地图控制器是否初始化完成,避免在地图未创建时调用相机方法报错- 使用
animateCamera会带动画效果平滑移动地图,若需要无动画的直接跳转,可替换为moveCamera - 这段逻辑放在
Consumer2的builder中,确保每次LocationNotifier或HotspotNotifier更新时都会触发,实现标记与地图中心的同步更新
内容的提问来源于stack exchange,提问作者Schleis
相关产品推荐
相关产品推荐

