Flutter如何在Widget中声明int index,用Provider加载Firebase点位生成谷歌地图标记
问题修复方案
你只需要遍历Provider拿到的门店列表,将每一条数据转换为Marker实例,再整合成Set<Marker>传给GoogleMap组件即可,不需要手动声明index变量。
核心修改逻辑
注释的GoogleMap部分修改如下,同时可以删掉State类中冗余的Completer<GoogleMapController> mapController声明,直接使用组件传入的实例即可:
@override Widget build(BuildContext context) { StoreNotifier storeNotifier = Provider.of<StoreNotifier>(context); // 遍历门店列表生成Marker集合 final Set<Marker> storeMarkers = storeNotifier.storeList.map((store) { return Marker( markerId: MarkerId(store.storeId), icon: BitmapDescriptor.defaultMarkerWithHue(_marker), position: LatLng( store.location.latitude, store.location.longitude, ), infoWindow: InfoWindow( title: store.name, snippet: store.address, ), ); }).toSet(); return GoogleMap( initialCameraPosition: _initialPosition, markers: storeMarkers, onMapCreated: (controller) { // 直接用widget传入的mapController实例即可 widget.mapController.complete(controller); }, ); }
可优化点
- 可以加加载状态判断:如果
storeNotifier.storeList.isEmpty,可以先返回加载中组件,避免空列表时地图无提示 Store模型的fromMap方法建议增加字段判空逻辑,避免Firebase返回空值时出现异常:
Store.fromMap(Map<String, dynamic> data) { storeId = data['storeId'] ?? ''; name = data['name'] ?? ''; address = data['address'] ?? ''; image = data['image'] ?? ''; location = data['location'] ?? GeoPoint(0, 0); }
内容的提问来源于stack exchange,提问作者eight
相关产品推荐
相关产品推荐

