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:
How do I convert the snapshot to an List ?
Thanks
I made the changes suggested and now I get this error:
UPDATE:
I tried the code from Usama and not I get this error:
2
Answers
You need to iterate through
snapshot.data?.docs
which can return events List.First you need to get collections then you need to convert querysnapshot to your custom object list.
Here is the code to achieve this