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:

@override
  void initState() {
    super.initState();

    talksStream = firestore
        .collection("talks")
        .where("active", isEqualTo: true)
        .snapshots()
        .listen((event) {
      updateincomingTalks(event.docs);
    });
  }

Then you have a function like this to handle each document in a map function

  updateincomingTalks(
      List<QueryDocumentSnapshot<Map<String, dynamic>>> eventDocs) {
    setState(() {
      incomingTalks = eventDocs.length.toString();
      if (eventDocs.length > 0) {
        eventDocs.map((element) {
          return (TalkSession.fromJson(element.data()));
        }).toList();
      }
    });
  }

My TalkSession class is a class I made which reflects the documents in the firestore collection. Having fromJson and toJson functions saves a lot of time when wanting to create or map into custom objects.

import 'package:cloud_firestore/cloud_firestore.dart';

class TalkSession {
  final String createdbyuid;
  final String createdbyname;
  final String searchertype;
  final bool matched;

  final Timestamp created;

  late String id;
  late bool active;

  TalkSession(this.createdbyuid, this.createdbyname, this.searchertype,
      this.matched, this.active, this.created);

  TalkSession.fromJson(Map<String, dynamic> json)
      : createdbyuid = json['createdbyuid'],
        createdbyname = json['createdbyname'],
        matched = json['matched'],
        active = json['active'],
        searchertype = json['searchertype'],
        created = json['created'];

  Map<String, dynamic> toJson() => {
        'createdbyuid': createdbyuid,
        'createdbyname': createdbyname,
        'matched': matched,
        'searchertype': searchertype,
        'active': active,
        'created': created
      };
}

0 0 votes
Article rating
Subscribe
Notify of
guest

0 Comments
Inline Feedbacks
View all comments