Reputation: 567
I am building a desktop application for Windows using Flutter. I am trying to retrieve all of the documents IDs from a collection in FireStore using the package firedart (as the official FireStore package does not support Windows).
This is a simple code to get the documents from a collection:
FirebaseAuth.initialize(apiKey, VolatileStore());
Firestore.initialize(projectId);
CollectionReference stream = Firestore.instance.collection('users');
final data = await stream.get();
print(data);
The output of this print will be a list of arrays where each one has the path to the document and the values sorted inside the document. for example:
[/users/1dfU7emalRX89z5zlfX0AQLqehq1 {url: '', name: '', height:'' , weight: '',}, /users/JF6PMb2q9Igsb56jgPRs1DGzJ0d2{url: '', name: '', height:'' , weight: '',}]
How can I print the Ids only to a list?
Upvotes: 0
Views: 263
Reputation: 71
you can get id from this collection by convert value to string and split this string to get it
'''
/// to save return id only
List<String> ids = [];
/// first store return data in List<dynamic>
List<dynamic> list = [
"/users/1dfU7emalRX89z5zlfX0AQLqehq1 {'url': '', 'name': '', 'height':'' , 'weight': '',}",
"/users/JF6PMb2q9Igsb56jgPRs1DGzJ0d2{url: '', 'name': '', 'height':'' , 'weight': '',}"
];
/// forEach element in list convert it to string
list.forEach((element) {
/// it will return part of string as '/users/1dfU7emalRX89z5zlfX0AQLqehq1 '
final String firstPartString = element.toString().split('{').first;
/// split new string by / and it the last item (it is id)
final String id = firstPartString.split('/').last;
/// adding id to ids list (trim to remove any prefix of suffix space)
ids.add(id.trim());
});
print(ids);
'''
Upvotes: 1
Reputation: 154
As I found from linked package's docs, API of the library you are using is similar to the official one.
This answer might help - you can get document ID when you have a reference to the document
Upvotes: 0