How to get document id in firestore flutter using QuerySnapshot

Viewed 739

This is the image of my firesoter database

I am trying to get data (In real-time) from my database using QuerySnapshot. and I need to update my data as well. This is my method and I don't know how to get my documentID in this method.

class LoadData extends StatefulWidget {
  const LoadData({Key? key}) : super(key: key);

  @override
  _LoadDataState createState() => _LoadDataState();
}

class _LoadDataState extends State<LoadData> {
  //Read Data in realTime Snapshot
  final Stream<QuerySnapshot> _cupCakeStream = FirebaseFirestore.instance
      .collection('cupcake')
      .snapshots(includeMetadataChanges: true);

  @override
  Widget build(BuildContext context) {
    return StreamBuilder<QuerySnapshot>(
      stream: _cupCakeStream,
      builder: (BuildContext context, AsyncSnapshot<QuerySnapshot> snapshot) {
        if (snapshot.hasError) {
          return Text('Something went wrong');
        }

        if (snapshot.connectionState == ConnectionState.waiting) {
          return Text("Loading");
        }

        return ListView(
          shrinkWrap: true,
          children: snapshot.data!.docs.map((DocumentSnapshot document) {
            Map<String, dynamic> data =
                document.data()! as Map<String, dynamic>;
            print(data); //**Print collection only..I need to get documentID with each collection**
            return ListTile(
              title: Text(data['cupcake_name']),
              subtitle: Text(data['description']),
            );
          }).toList(),
        );
      },
    );
  }
}
1 Answers

document is a DocumentSnapshot and has an id property.

So, the following should do the trick:

    return ListView(
      shrinkWrap: true,
      children: snapshot.data!.docs.map((DocumentSnapshot document) {
        Map<String, dynamic> data =
            document.data()! as Map<String, dynamic>;
        print(data); 
        
        print(document.id);   // <= Should print the doc id             

        return ListTile(
          title: Text(data['cupcake_name']),
          subtitle: Text(data['description']),
        );
      }).toList(),
    );
Related