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:

  void initState() {

    talksStream = firestore
        .where("active", isEqualTo: true)
        .listen((event) {

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

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

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.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
Notify of

Inline Feedbacks
View all comments