{"id":878,"date":"2021-05-10T00:07:35","date_gmt":"2021-05-09T22:07:35","guid":{"rendered":"https:\/\/fileidea.com\/?p=878"},"modified":"2021-05-10T00:09:11","modified_gmt":"2021-05-09T22:09:11","slug":"map-firestore-documents-in-flutter","status":"publish","type":"post","link":"https:\/\/fileidea.com\/2021\/05\/10\/map-firestore-documents-in-flutter\/","title":{"rendered":"Map Firestore documents in Flutter"},"content":{"rendered":"\n
Map Firestore documents in Flutter into a custom object can be tricky, but it doesn’t have to be. Let’s say you have a firestore collection query like this inside your initState <\/strong>for listening on changes from a collection:<\/p>\n\n\n Then you have a function like this to handle each document in a map function<\/p>\n\n\n My TalkSession <\/strong>class is a class I made which reflects the documents in the firestore collection. Having fromJson <\/strong>and toJson<\/strong> functions saves a lot of time when wanting to create or map into custom objects. <\/p>\n\n\n Map Firestore documents in Flutter into a custom object can be tricky, but it doesn’t have to be. Let’s say you have a firestore collection query like this inside your initState for listening on changes from a collection: Then you have a function like this to handle each document in a map function My TalkSession … <\/p>\n\n@override\n void initState() {\n super.initState();\n\n talksStream = firestore\n .collection("talks")\n .where("active", isEqualTo: true)\n .snapshots()\n .listen((event) {\n updateincomingTalks(event.docs);\n });\n }\n<\/pre><\/div>\n\n\n
\n updateincomingTalks(\n List<QueryDocumentSnapshot<Map<String, dynamic>>> eventDocs) {\n setState(() {\n incomingTalks = eventDocs.length.toString();\n if (eventDocs.length > 0) {\n eventDocs.map((element) {\n return (TalkSession.fromJson(element.data()));\n }).toList();\n }\n });\n }\n<\/pre><\/div>\n\n\n
\nimport 'package:cloud_firestore\/cloud_firestore.dart';\n\nclass TalkSession {\n final String createdbyuid;\n final String createdbyname;\n final String searchertype;\n final bool matched;\n\n final Timestamp created;\n\n late String id;\n late bool active;\n\n TalkSession(this.createdbyuid, this.createdbyname, this.searchertype,\n this.matched, this.active, this.created);\n\n TalkSession.fromJson(Map<String, dynamic> json)\n : createdbyuid = json['createdbyuid'],\n createdbyname = json['createdbyname'],\n matched = json['matched'],\n active = json['active'],\n searchertype = json['searchertype'],\n created = json['created'];\n\n Map<String, dynamic> toJson() => {\n 'createdbyuid': createdbyuid,\n 'createdbyname': createdbyname,\n 'matched': matched,\n 'searchertype': searchertype,\n 'active': active,\n 'created': created\n };\n}\n\n<\/pre><\/div>","protected":false},"excerpt":{"rendered":"