Home > Software engineering >  Getting the document ID of a ListTile item
Getting the document ID of a ListTile item

Time:01-20

I am trying to get the document ID of a ListTile from Firebase in Flutter when that Tile is tapped:

Stream collectionStream = FirebaseFirestore.instance.collection('items').snapshots();
Stream documentStream = FirebaseFirestore.instance.collection('items').doc('ABC123').snapshots();

class AllItemList extends StatefulWidget {
  @override
  _AllItemListState createState() => _AllItemListState();
}

class _AllItemListState extends State<AllItemList> {
  final Stream<QuerySnapshot> _itemStream = FirebaseFirestore.instance.collection('items').snapshots();

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

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

        return ListView(
          //physics: const NeverScrollableScrollPhysics(),
          shrinkWrap: true,
          children: snapshot.data!.docs.map((DocumentSnapshot document) {
            Map<String, dynamic> data = document.data()! as Map<String, dynamic>;
            return ListTile(
              title: Text(data['title']),
              subtitle: Text(data['userName']),
              trailing: Text('Priority: ' data['priority'].toString()),
              onTap: (){
                print('This Document ID');
              },
            );
          }).toList(),
        );
      },
    );
  }
}

I checked out this post: Flutter - How can i query the same document id - on the next page - as a ListTile that was previously clicked

but I'm still stuck

CodePudding user response:

My implementation might be a little too different from yours, but I use:

document.reference.id

Example:

_dataSource.snapshots().listen((event) {
  final List<Thing> documents = event.docs.map((document) => document
    .data()
    .rebuild((doc) => doc..firebaseDocumentId = document.reference.id)).toList();
    // doing my biz logic here

});

Ignore the .rebuild that's just part of the built_value lib I am using

  •  Tags:  
  • Related