Fetching rows with a particular value of child Firebase Flutter - firebase

I'm working with Flutter and Firebase (Real-time database). There is some data stored in the db and I want to compare the email (child) of the parent and only want to display the parents containing that particular email. Currently, it is fetching all rows. I think fetching through key value pair would do the work. But I dont know the syntax and unable to find help regarding it. Please help me out.
void myfunc() {
databaseReference.once().then((DataSnapshot snapshot) {
print('Data : ${snapshot.value}');
});
}

try with
yourRef.orderByChild("email").equalTo('abs#abc.com');
Read Query Data

Related

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.

Flutter and Firebase: Return all images from Firebase Storage

I have seen a few articles written online by people pertaining to be able to do this, but they only tell you how to do this with a specific, controlled list of images where they also know all the filenames beforehand.
There is also this "answer" posted here: Flutter - Get all images from firebase storage which does not actually resolve this issue at all as it suggests a .listAll() method for the recommended plugin, but there is no such method as .listAll() using the suggested plugin.
I need to be able to not know how many images are in Firebase storage, or what they might be called, just to return everything stored there.
UPDATE:
So because Firebase is full of so many limitations that it hardly qualifies as a database at all, it seems we may have to keep the images in Firebase Storage and a reference list of these in a Firebase Realtime Database Document.
I am stuck on the actual implementation of this however, as I am not even sure firstly how best to go about this. What I am attempting to do is store all the Storage image URLs in an array (if this is not the best way to do this, let me know!):
Firebase Structure
collection -> document -> fields
userData profileImages URLs (array)
My first issue is that I don't know how to append new data to the existing array, it seems to just overwrite it each time I add a new item so that I only ever have one string in the array in the database:
Firestore.instance.collection('userData').document('profileImages').updateData({
'URLs': _uploadedFileURL,
});
Then after this I am also not sure how to actually retrieve the full array of data later when I need it:
Container(
child: StreamBuilder(
stream: Firestore.instance.collection('userData').document('profileImages').snapshots(),
builder: (BuildContext context, AsyncSnapshot<DocumentSnapshot> snapshot) {
if (!snapshot.hasData) {
return LoadingAnimationBasic();
}
if (snapshot.data.data == null) {
return LoadingAnimationBasic();
} else {
return ListView(
shrinkWrap: true,
children: _buildProfileGallery(snapshot),
);
}
},
),
),
And then the function:
_buildProfileGallery(AsyncSnapshot<DocumentSnapshot> snapshot) {
int test = snapshot.data["URLs"].length;
print('URLs in List: ' + test.toString());
return snapshot.data.data.map(???);
}
I have no idea what to put as the parameters of this map, as the hint text is insane:
MapEntry(K2, V2> f(String key, V value)
I can't even begin to guess what this means.
Am I on the right track? Am I on the right planet?
The ability to list files was added to Firebase's client-side SDKs for Android, iOS and JavaScript last year, but has not yet landed in the FlutterFire bindings.
The answer to the question you linked, refers to a pull request on the FlutterFire open-source project that adds this functionality. So while somebody wrote code to allow listing of files in Flutter too, this code hasn't been added to a release so far. So the only way to use that code now, is to build your own version of the FlutterFire library for firebase_storage.
Without the ability to list files in the Firebase Storage API, you'll have to revert back to what everyone did before this feature was added: keeping a list of the files in a secondary location, such as the Firebase Realtime Database or Cloud Firestore.

How to create custom index for firestore query

I need to be able to retrieve some data from my cloud firestore database where certain conditions are met and then order that data but I am unable to get my query to work. I've read that if you simply run the query then your log should provide you a link to automatically create the custom index but unfortunately within my flutter logs or the android studio logcat i'm not getting any links. I know you can create the custom indexes manually in the firebase console so i'm happy to do this but I dont know how I would create the index for this.
firestore.collection('users').where('organisation_id', isEqualTo: _authenticatedUser.organisationId)
.orderBy('first_name').getDocuments()
I just need to know how to create the composite index for this query so that it will work in my app
I was able to get a link in my console log by surrounding the firestore query with a try catch and printing out the platform exception which generated the direct link, thanks to Dougs answer
try {
snapshot = await firestore.collection('users').where(
'organisation_id', isEqualTo: _authenticatedUser.organisationId)
.orderBy('first_name').getDocuments();
} catch(e){
print(e);
}

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.

Getting data without a key. Only with information on child nodes

I'm having a really hard time understanding how Nosql works so I hope someone can help me understand it a bit better.
I'm trying to make a simple chat application (One to one chat support and chat groups) and want to dislay a list of all the conversations that the current user is in. This is my table for it.
I tried getting the data in several ways. But what I currently have is this (Which should work according to the internet, but doesn't).
_membersRef.equalTo(1508, key: '1508').once().then((DataSnapshot snap) {
print(snap.value);
});
I also tried
_membersRef.startAt(1508).endAt(1508).once().then((DataSnapshot snap) {
print(snap.value);
});
What I want my code to do is return all records that have my account_id in them (1508 in this case). So it should return the record "one".
So if I change the uid in the code to 1509 it should return "One" and "two". How can I make this happen?
To get the key one try this:
_membersRef.orderByChild('1508').equalTo(true).once().then((DataSnapshot snap) {
print(snap.value);
});
the snapshot is at child members then you order it according to child 1508 which is equalTo(true).

Resources