![](/img/trans.png)
[英]How to retrieve all documents from a collection in Firestore optimizing reads?
[英]How to retrieve all documents in a collection in Firebase and add to a list?
我在 Firebase 中有一個集合,我正在嘗試檢索並將其添加到列表中:
我還定義了一個事件 model。 在將事件添加到列表之前,我想使用從 Firebase 讀取的數據創建一個事件 object。
事件模型:
class Event {
String eid;
String title;
String location;
String start;
String end;
String instructor;
String image;
String description;
Event({
required this.eid,
required this.title,
required this.location,
required this.start,
required this.end,
required this.instructor,
required this.image,
required this.description
});
String getEid() {
return eid;
}
String getTitle() {
return title;
}
String getLocation() {
return location;
}
String getStart() {
return start;
}
String getEnd() {
return end;
}
String getInstructor() {
return instructor;
}
String getImage() {
return image;
}
String getDescription() {
return description;
}
void setEid(String eid) {
this.eid = eid;
}
void setTitle(String title) {
this.title = title;
}
void setLocation(String location) {
this.location = location;
}
void setStart(String start) {
this.start = start;
}
void setEnd(String end) {
this.end = end;
}
void setInstructor(String instructor) {
this.instructor = instructor;
}
void setImage(String image) {
this.image = image;
}
void setDescription(String description) {
this.description = description;
}
}
這是我到目前為止所擁有的。 我正在創建事件對象列表,然后嘗試獲取整個集合,對於集合中的每個文檔,我正在創建事件 object 並嘗試將其添加到列表中。 我不確定這是否正確。
List<Event> _events = [];
Future<UserProfile> getUserProfile() async {
try {
final FirebaseAuth auth = FirebaseAuth.instance;
final snapshot = await FirebaseFirestore.instance.collection('events').get();
snapshot.docs.forEach((doc) {
Map<String, dynamic>? data = snapshot.data();
Event event = Event(
eid: data?['eid'],
title: data?['title'],
...
});
一個更好的方法是Map<String, dynamic>
到Event
class object 的對話,應該使用Event
class 的factory
構造函數來完成,並為每個屬性設置一個默認值,所以如果出現 null,你的應用程序不會崩潰,它會有一個默認值並且可以正常工作,如下所示:
將此添加到您的Event
class:
factory Event.fromMap(Map<String, dynamic>? map) {
return Event(
eid: map?["eid"] ?? "defaultValue,"
title: map?["title"] ?? "defaultValue",
location: map?["location"] ?? "defaultValue",
start: map?["start"] ?? "defaultValue,"
end: map?["ends"] ?? "defaultValue,"
instructor: map?["instructor"] ?? "defaultValue,"
image: map?["image"] ?? "defaultValue,"
description: map?["description"] ?? "defaultValue",
);
}
然后不執行您的方法,而是使用以下方法將您自己從樣板代碼中解救出來:
Event event = Event.fromMap(snapshot.data() as Map<String, dynamic>);
_events.add(event);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.