WFlutter Firebase- Get only one field of data from firebase document - firebase

I have a collection of users and in each document, I want only to get on data which is the array, is there any possible way to only get on, or do I need the whole document?

Try this please. Because its a field, as far as I know, we need to get the whole document first. Hope its help you.
await Firestore.instance.collection('users').document(your document id)
.get().then((Snapshot snapshot){
print(snapshot.data['userCart'])
});

Related

Firebase Firestore - Best way to call a bunch of where gets?

I have an array of user emails that I want to then pull from firebase each of the corresponding user documents from a collection where one of the email matches. I don't want to pull the whole collection as it would be expensive. What is the easiest way to do this? I tried for looping over the array with individual gets to firebase but ran into promise issues as I want to do something in Javascript with them right after.
Thanks so much!
based on what i understood from your question i can only think of using await Promise.all() - you can look into this here.
as an example you could pass an array of promises to await Promise.all() so you could do
const res = await Promise.all(
array.map( x => db.collection('users')
.where('email' , '==', x.email).limit(1).get());
mind you that in this example you would still have to process the result as they will return a snapshot not a document ...
Update:
Hey there, i just noticed that you can use in operator in firebase query, which will return the values matching in a given array.
i'm not sure but maybe using it might be suitable in your use-case you can check the documentation here

Flutter & Firebase: How to populate an array and then later, return all the contents

I have been trying to get arrays working in Firebase, and I am aware that there are a lot of references and discussions about this online, and I have read through all of these and none of it works.
First off, the Firebase side. The structure containing the array and two example strings inside it:
Firebase Structure
collection -> document -> fields
userData profileImages URLs (array)
: https://firebasestorage.googleapis.com/v0/b/app-138804.appspot.com/o/jRwscYWLs1DySLMz7jn5Yo2%2Fprofile%2Fimage_picker4459623138678.jpg?alt=media&token=ec1043b-0120-be3c-8e142417
: https://firebasestorage.googleapis.com/v0/b/app-138804.appspot.com/o/jRwscYWLs3872yhdjn5Yo2%2Fprofile%2Fimage_picker445929873mfd38678.jpg?alt=media&token=ec3213b-0120-be9c-8e112632
The first issue I am facing is writing to this array in the database:
Firestore.instance.collection('userData').document('profileImages').updateData({
'URLs': _uploadedFileURL,
});
Whenever I add data to this array, it just overwrites the existing data. I need to be able to keep all the existing data intact and simply add the current new line to the array.
Once this is working, I then need to be able to return all of the strings in this array without needing to know how many of them there will be.
For this part, I basically have nothing at this point. I could show some of the things I have tried based on suggestions from other articles on this, but none of it is even close to working correctly.
im assuming that _uploadedFileURL is a String, and you are updating the property URLs, that's why your data gets overwritten, because you are changing the URLs value to a single string which is _uploadedFileURL. to solve this issue, simply get the current data inside profileImages before commiting the update. like so
final DocumentSnapshot currentData = await Firestore.instance.collection('userData').document('profileImages').get();
Firestore.instance.collection('userData').document('profileImages').updateData({
'URLs': [
...currentData.data['URLs'],
_uploadedFileURL
],
});
and for the second part of your question, all you need is to query for the profileImages
Future<List<String>> _getProfileImages() {
final document = Firestore.instance.collection('userData').document('profileImages').get();
return document.data['profileImages]
}
the result of the get method will be a DocumentSnapshot, and inside the data property will access the profileImages which is a List<String>.
Ok guys and girls I have worked this out. Part 1: appending data to an array in Firebase.
Firestore.instance.collection('userData').document('profileImages').updateDataupdateData({
'URLs':FieldValue.arrayUnion([_uploadedFileURL]),
});
Where _uploadedFileURL is basically a string, for these purposes. Now I have read that arrayUnion, which is super groovy, is only available in Cloud Firestore, and not the Realtime Database. I use Cloud Firestore so it works for me but if you are having issues this might be why.
Now what is extra groovy about Cloud Firestore is that you can similarly remove an element from the array using:
Firestore.instance.collection('userData').document('profileImages').updateDataupdateData({
'URLs':FieldValue.arrayRemove([_uploadedFileURL]),
});
So how to get this data back out again. A simple way I have found to get that data and chuck it into a local array is like so:
List imageURLlist = [];
DocumentReference document = Firestore.instance.collection('userData').document('profileImages');
DocumentSnapshot snapshot = await document.get();
setState(() {
imageURLlist = snapshot.data['URLs'];
});
From here at least you have the data, can add to it, can remove from it and this can be a platform for you to figure out what you want to do with it.

Retrieving snapshots from firestore sub-collection to dart/flutter object

New here. I've googled everything and can't figure this out.
The first two functions below work flawlessly the third always return null immediately without calling my ListFromSnapShot function, which just turns the map into a list. I am assuming
I'm not calling the Firestore correctly but I have no idea how to do this properly.
final CollectionReference customerCollection = Firestore.instance.collection('customers');
final CollectionReference jobCollection = Firestore.instance.collection('jobs');
// get user doc stream
Stream<UserData> get userData {
return customerCollection.document(uid).snapshots()
.map(_userDataFromSnapshot);
}
//Returns only snapshots with matching customer name to StreamProvider object
Stream<List<Job>> get jobQuery {
return jobCollection.where('customerName', isEqualTo: currentCustomer.companyName)
.snapshots()
.map(_jobListFromSnapshot);
}
//The following always returns Null
Stream<List<JobSectionModel>> get jobQuerySections {
return jobCollection.document('Family Dollar').collection('sections')
.snapshots()
.map(_jobSectionListFromSnapshot);
This is my database structure
Base Collection
Subcollection
Any help would be greatly appreciated.
The code above does work, the problem, after several frustrating days, ended up being random spaces in the firestore path. I'm posting this as an answer because after googling this there were many others with a similar problem and I don't want them to go through the same frustration. Firestore will not show this until you literally click on the path name and it will not crash your program, it just returns nothing.
Do yourself a favor and use the .trim() function when adding data and if you do it manually on firestore make sure there's no trailing spaces.
Also I rebuilt the code as follows which also works (without spaces of course)
Stream<QuerySnapshot> getjobQuerySections(BuildContext context) async*{
yield* jobCollection.document('T-MOBILE').collection('whyspaces').snapshots();
Hope this helps someone. Good Luck

Flutter Firestore save field as a String?

I am facing a problem with Flutter and Firebase Firestore. I want to take one of the current User's label, and save it as a string. I have already figured out how to find the currentUserID, so that isn't the problem. I just can't figure out how to target the "preference" label in my database. Here is my code for trying to declare it as a string:
String _checkPreference(DocumentSnapshot document) {
Firestore.instance.collection(currentUserId).document('preference').toString();
return _checkPreference(document);
}
The goal is then later to be able to do something like this:
return Text(_checkPreference(document));
Bit I am not really sure what to pass in, and if my method to get it is even correct. Thanks for reading, any help is appreciated!

Flutter Firebase Children Count

I'm currently creating a dashboard application for my main application, this dashboard is able to display in charts the demography of the users that uses the app. I use Firebase Database as the backend. The JSON tree of my DB is as shown below. My question is, how do I get the amount of data with a specific value of a key? Example: the number of children with the value 'Pria' for the key 'jk' is 2.
My Backend JSON Tree:
So far, I'm able to get all of the data using:
DatabaseReference itemRef = FirebaseDatabase.instance.reference().child('data_pengguna');
And I've also tried the codes below, but it doesn't seem to work:
int jmlPria;
FirebaseDatabase.instance
.reference()
.child('data_pengguna')
.orderByChild('jk')
.equalTo('Pria')
.once()
.then((onValue) {
Map data = onValue.value;
jmlPria = data.length;
});
But I haven't successfully filtered the data and put it inside a variable, can anyone help me?
Many thanks in advance.
That last snippet looks correct, jmlPria should have the number of children.
But the value of jmlPria will only be set to the latest value inside the then() callback. Make sure that Text($jmlPria) is inside the then() callback. Outside of that, jmlPria will not have the correct value.
Also see Doug's great blog post on asynchronous programming.

Resources