如何在Firebase中检索集合中的所有文档并添加到列表中?

jrcvhitl  于 2022-11-25  发布在  其他
关注(0)|答案(1)|浏览(123)

我在Firebase中有一个集合,我试图检索并添加到列表中:

我还定义了一个事件模型。在将事件添加到列表之前,我想使用从Firebase读取的数据创建一个Event对象。

事件模型:

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;
  }
}

这是我目前所拥有的。我正在创建Event对象列表,然后尝试获取整个集合,对于集合中的每个文档,我正在创建Event对象并尝试将其添加到列表中。我不确定这是否正确。

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'],
              ...
      });
lbsnaicq

lbsnaicq1#

一个更好的方法是将Map<String, dynamic>转换为Event类对象,应该使用Event类的factory构造函数,并为每个属性设置默认值,这样,如果某个属性为空,您的应用程序不会崩溃,它将具有默认值并正常工作,如下所示:
将以下代码添加到您的Event类:

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);

相关问题