如何从Firebase Firestore获取地理点转为Flutter Polyline所需的List<LatLng>
问题描述
我在Firestore数据库的文档集合中,某文档存储了地理点数据,希望在Flutter应用的Google Map上基于这些点绘制Polyline。但Polyline的points参数要求为List<LatLng>类型,示例代码如下:
points: <LatLng>[ LatLng(0, 0), LatLng(1, 1), ],
从Firestore获取这些点时,得到的是List<dynamic>类型,直接使用会触发以下错误:
[ERROR:flutter/runtime/dart_vm_initializer.cc(41)] Unhandled Exception: type 'List<dynamic>' is not a subtype of type 'List<LatLng>'
请问如何将Firestore中的点转为List<LatLng>,或如何在数据库中存储LatLng,以实现根据任意数量的点绘制Polyline?
解决方案
1. 转换Firestore返回的动态列表为List
从Firestore获取的动态列表中,每个地理点应为Firestore的GeoPoint类型。你可以通过遍历列表,将每个GeoPoint实例转换为LatLng:
假设从Firestore文档中读取的字段名为routePoints,代码示例:
// 从Firestore文档获取原始动态列表 List<dynamic> rawPoints = documentSnapshot.data()['routePoints']; // 转换为符合要求的List<LatLng> List<LatLng> polylinePoints = rawPoints.map((point) { return LatLng(point.latitude, point.longitude); }).toList();
转换完成后,直接将polylinePoints传入Polyline的points参数即可。
2. 优化Firestore存储方式(可选)
如果想从根源减少类型转换的步骤,推荐直接使用Firestore的GeoPoint类型存储地理点:
写入数据时,将List<LatLng>转换为List<GeoPoint>再存入:
// 待存储的路线点列表 List<LatLng> routePoints = [LatLng(0, 0), LatLng(1, 1)]; // 转换为Firestore支持的GeoPoint列表 List<GeoPoint> firestorePoints = routePoints.map((latLng) { return GeoPoint(latLng.latitude, latLng.longitude); }).toList(); // 写入Firestore文档 await FirebaseFirestore.instance.collection('routes').doc('your_doc_id').set({ 'routePoints': firestorePoints, });
这种存储方式符合Firestore的地理数据规范,读取时只需按上述转换方法即可得到List<LatLng>,类型逻辑更清晰。
内容的提问来源于stack exchange,提问作者OverdoseB12
相关产品推荐
相关产品推荐

