skip to Main Content

I have a snapshot from firestore that I need to convert to a List list.

I have been reading about AsyncSnapshot snapshots and they come back as json, correct?

I need to convert the data in the snapshot to a list of the type "Events" for an appointment screen.

Here is the data model for Events:

String? id;
  String? eventName;
  DateTime? eventStartTime;
  String? eventDuration;
  DateTime? eventDate;
  String? eventDescription;
  String? userId;
  String? companyId;

I also have a function in my code for converting json to a map and then I type cast it as a list.

factory Events.fromJson(DocumentSnapshot doc) {
    Map data = doc.data() as Map<String, dynamic>;
    return Events(
      id: doc.id,
      eventName: data['eventName'],
      eventStartTime: (data['eventStartTime'] as Timestamp).toDate(),
      eventDuration: data['eventDuration'],
      eventDate: (data['eventDate'] as Timestamp).toDate(),
      eventDescription: data['eventDescription'],
      userId: data['userId'],
      companyId: data['companyId'],
    );
  }

This is where I am trying to execute this code:

if (snapshot.connectionState == ConnectionState.waiting) {
                return const Center(child: CircularProgressIndicator());
              } else {
                if (snapshot.hasData && snapshot.data!.docs.isNotEmpty) {
                  List<Events> eventsList =
                      Events.fromJson(snapshot.data) as List<Events>;   <<< HERE
                  return _buildTableCalendar(eventsList);
                } else {
                  return _buildTableCalendar();
                }
              }

This code is inside a StreamBuilder

I get an error when I try to execute the Events.fromJson() line. Here is the error:
enter image description here

How do I convert the snapshot to an List ?

Thanks

I made the changes suggested and now I get this error:
enter image description here

UPDATE:
I tried the code from Usama and not I get this error:
enter image description here

2

Answers


  1. You need to iterate through snapshot.data?.docs which can return events List.

    if (snapshot.hasData && snapshot.data!.docs.isNotEmpty) {
      List<Events> eventsList =
          snapshot.data?.docs.map((e) => Events.fromJson(e)).toList() ??
              [];
    
    Login or Signup to reply.
  2. First you need to get collections then you need to convert querysnapshot to your custom object list.

    Here is the code to achieve this

    QuerySnapshot<Map<String, dynamic>> querySnapshot = await
            _db.collection("your collection).get();
          if (querySnapshot.docs.isNotEmpty) {
            List<Events> events = [];
            for (var snapshot in querySnapshot.docs) {
              Events event = Events.fromJson(snapshot.data());
              events.add(event);
            }
          }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search