【发布时间】:2021-10-26 11:03:13
【问题描述】:
我想检查集合文档中是否存在名为isfeatured 的字段?如果某些字段在 firestore 数据库的文档中不存在,我会得到以下错误,即使我正在使用?? 处理它,如下所示。
错误状态:无法获取 DocumentSnapshotPlatform 上不存在的字段
以下是我如何从 firestore 获取数据
Stream<List<Restaurant>> get getAllRestaurants => FirebaseFirestore.instance.collection('restaurants').snapshots().map(_restaurantsDataFromSnapshot);
// Mapping Restaurant data
List<Restaurant> _restaurantsDataFromSnapshot(QuerySnapshot snap) {
List<Restaurant> restaurantList = [];
snap.docs.forEach((element) {
restaurantList.add(Restaurant.fromJson(element));
});
return restaurantList;
}
只有 fromJson 类的 Restaurant 函数。大多数人建议将exists 用于字段,但我不能将其用于字段。它适用于整个QueryDocumentSnapshot。 fromJson 用于映射数据。
factory Restaurant.fromJson(QueryDocumentSnapshot map) {
return Restaurant(
// Getting other feilds
isFeatured: map.data()['isFeatured'] ?? false,
);
}
编辑:
我正在使用带有Streambuilder 的流
class MainClass extends StatelessWidget {
@override
Widget build(BuildContext context) {
StreamProvider restaurantsProvider = StreamProvider<List<Restaurant>>.value(
initialData: [],
value: DatabaseService().getAllRestaurants,
);
return MultiProvider(
providers: [
restaurantsProvider,
// Some other providers
],
child: HomeView(),
);
}
}
如果有人感兴趣,请填写Restaurant class
import 'package:cloud_firestore/cloud_firestore.dart';
class Restaurant {
String restaurantID;
String name;
double rating;
String availabilityTime;
int orders;
List<String> restaurantCtg;
String imageUrl;
bool isFeatured;
String address;
bool availableStatus;
String coordinates;
Restaurant({
this.restaurantID,
this.name,
this.rating,
this.availabilityTime,
this.orders,
this.restaurantCtg,
this.imageUrl,
this.isFeatured,
this.address,
this.availableStatus,
this.coordinates, });
Map<String, dynamic> toMap() {
return {
'restaurantID': restaurantID,
'name': name,
'rating': rating,
'availabilityTime': availabilityTime,
'orders': orders,
'restaurantCtg': restaurantCtg,
'imageURL': imageUrl,
'isFeatured': isFeatured,
'address': address,
'availableStatus': availableStatus,
'coordinates': coordinates,
}; }
factory Restaurant.fromJson(QueryDocumentSnapshot map) {
return Restaurant(
restaurantID: map.data()['restaurantID'] ?? "",
name: map.data()['name'] ?? "",
rating: map.data()['rating'] ?? 0.0,
orders: map.data()['orders'] ?? 0,
restaurantCtg: List<String>.from(map.data()['restaurantCtg']),
imageUrl: map.get('imageURL').exist ? map.data()['imageURL'] : "",
isFeatured: map.data()['isFeatured'] ?? false,
address: map.data()['address'] ?? "",
availabilityTime: map.data()['availabilityTime'] ?? "09:00-18:00",
availableStatus: map.data()['availableStatus'] ?? true,
coordinates: map.data()['coordinates'] ?? "",
);
}
}
【问题讨论】:
-
您是否在 StreamBuilder 中使用流?
-
@VictorEronmosele 我忘了提到我正在使用这个流和
StreamProvider。我将为您编辑问题。 -
当您从
restaurant集合中获取所有文档时,这不是由缺少的文档生成的。可能存在其中isfeatured字段不存在或为空/null 的文档。为了检查,请记录您必须检查的所有文件
标签: flutter dart google-cloud-firestore stream snapshot