简体   繁体   中英

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;

}

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM