Flutter开发报错:CollectionReference无法赋值给Query参数类型
解决CollectionReference与Query类型不匹配问题
问题原因
Firebase Firestore默认返回的CollectionReference未指定泛型时,类型为CollectionReference<Object?>,而GeoFire的collection()方法需要的参数类型是Query<Map<String, dynamic>>,两者类型不兼容导致报错。
修复方案
直接在声明CollectionReference时指定泛型为Map<String, dynamic>,修改后的代码如下:
Stream nearbyATM() async* { GeoFirePoint point = geo.point(latitude: _position!.latitude, longitude: _position!.longitude); // 指定泛型为Map<String, dynamic> final CollectionReference<Map<String, dynamic>> atms = _firestore.collection("atms"); double radius = 100; String field = "location"; Stream<List<DocumentSnapshot>> stream = geo .collection(collectionRef: atms) .within(center: point, radius: radius, field: field); }
替代方案(类型转换)
如果不想修改原声明,也可以通过类型转换适配参数类型:
Stream nearbyATM() async* { GeoFirePoint point = geo.point(latitude: _position!.latitude, longitude: _position!.longitude); final CollectionReference atms = _firestore.collection("atms"); double radius = 100; String field = "location"; Stream<List<DocumentSnapshot>> stream = geo .collection(collectionRef: atms as CollectionReference<Map<String, dynamic>>) .within(center: point, radius: radius, field: field); }
内容的提问来源于stack exchange,提问作者Abdel
相关产品推荐
相关产品推荐

