John
John

Reputation: 2811

Flutter firestore get stream of document ids from a collection

I have the below Future that returns a String List, instead I would like to return Stream String List with the same document ids list, how do I do that?

Future<List<String>> getFollowingUidList(String uid) async{

final QuerySnapshot result = await FirebaseFirestore.instance.collection('following').doc(uid).collection('user_following').get();
final List<DocumentSnapshot> documents = result.docs;

List<String> followingList = [];

documents.forEach((snapshot) {
  followingList.add(snapshot.id);
});

return followingList;

}

Upvotes: 1

Views: 2782

Answers (1)

ErnestoC
ErnestoC

Reputation: 2904

According to the FlutterFire documentation, the snapshots() method of a CollectionReference will return a Stream. In Dart, Streams provide a map() method which allows you to easily transform the Stream and return a new one:

Transforms each element of this stream into a new stream event. Creates a new stream that converts each element of this stream to a new value using the convert function, and emits the result.

Based on this, it would be possible to return a new Stream with document IDs from the snapshots() Stream that comes from the CollectionReference. The CollectionReference Stream is of type QuerySnapshot, which, according to the documentation, contains a docs property of type List<QueryDocumentSnapshot>. To finish, this type can provide you with data from the DocumentSnapshots, including the ID of the document.

Stream<List<String>> returnIDs() {
    return Firestore.instance
        .collection('testUsers')
        .snapshots()
        .map((querySnap) => querySnap.docs //Mapping Stream of CollectionReference to List<QueryDocumentSnapshot>
        .map((doc) => doc.data.id) //Getting each document ID from the data property of QueryDocumentSnapshot
        .toList());
 }

I based this snippet on this example, which is full of useful scripts to use Streams with Firestore.

Upvotes: 2

Related Questions