Home > Net >  Flutter Firestore documentsnapshot to Map
Flutter Firestore documentsnapshot to Map

Time:12-25

For my flutter app, I am fetching a collection as a querysnapshot and converting it into a list using:

var dataList = snapShot.docs.map((e) => e.data()).toList();

Works like a charm, no issues till now.

Lately, I've been trying to manipulate the data in the collection and for that, I need the docId. But for some reason, the list does not have the docId included.

There should be a quick way of including the doc id while converting a snapshot to a list.

Can someone please help? Thanks.

CodePudding user response:

you can add e.id to your map.

var dataList = snapShot.docs.map((e) {
          Map value = e.data();
          value['docId'] = e.id;
          return value;
        }).toList();

Or You can create model class and add docId to model class below way.

you can return List of Object using this way

        return ref.snapshots().map((list) => list.docs.map((doc) => 
    Model.fromFirestore(doc)).toList());

your model class

    class Model {
      final String categoryId;
    
      Model({this.categoryId});
    
      factory Model.fromFirestore(DocumentSnapshot doc) {
        Map data = doc.data();
    
        return Model(
          docId: doc.id,
          categoryId: data['categoryId'],
        // other fields
        );
     }
    }
  • Related