Im trying to retrieve from firebase based on two conditions
`
final medResult = await userMedDB.userMedCollection
.where('userID', isEqualTo: Auth().uID)
.where('name', isEqualTo: medName)
.get();
`
is that code correct??
If you're trying to query google-cloud-firestore (you tagged with firebase-realtime-database, which is a different database) the code is correct.
If your query doesn't work when you add the second condition, you may be missing a composite index that is needed for this query. In that case, can any errors that may happen, log them to the console, and find the link in the error message. This link takes you directly to the Firebase console with all values filled in to create the correct index at the click of a button.
Related
I use Firebase in my Flutter project. I store a UserID in the array in a document in the Article Collection when someone favorites an article.
In a slide action of a list, I implemented a button that should either show a broken heart or a filled heart, depending on whether a user has already favorited the item or not.
I've already felt like I've scoured the whole internet for a method to see if the UserID of an article is in the array and somehow I'm at a loss.
Here is my Datastructure in Firebase
Although I can access this data via a stream, it only provides me with the articles with the corresponding UserID (which I need for a second page in my project)
Stream<List<Artikel>> readFavArtikel() => FirebaseFirestore.instance
.collection('artikel')
.where('userFavs', arrayContains: (globals.getUserID()))
.snapshots()
.map((snapshot) =>
snapshot.docs.map((doc) => Artikel.fromJson(doc.data())).toList());
I also know that by means of
documentSnapshot.get('userFavs')
can get a list of UserIDs. How can I then implement this in an if query to check whether this list contains a specific UserID
So my problem is that I know how to write in Firebase, update it, and read data... but now I need to get a specific field from a document and save it in some variable or string, and I am stuck there.
Picture of what I need
Here is a field I need to get.
Here is where I need to save it
So I need it to be saved so I can use it in code, specifically as an isEqual value. Because my goal is to display Players that play in that club. And every game its another club.
I found solution:
String? valueFromFirebase;
Future<String?> getData() async{
var a = await clubData.doc('Home').get();
setState(() {
valueFromFirebase= a['homeClubName'];
});
}
So when I need value from field ( in my case homeClubName) I just call string valueFromFirebase where I need it.
firstly you have link you app with firebase then you need to import 3 plugin firebase core plugin firebase Firestore and cloud firebase then you need to in your Main.dart here first you create a Class Then you control it by TextController then you'll post you data After the data will successfully post on firebase then you will get response from firebase.. Actually I'll work on Firebase you can say rule Put Get Update Delete & fetch in other word these are the Queries.
I am trying to make a firebase database call to retrieve all row of one particular column in the firebase database of my app and display it in a textbox in my flutter app.
That is, to retrieve all phone numbers in the Users table.
For instance, in SQL we can do like this:
SELECT (PhoneNumers) FROM Users
I am new in flutter/dart, I need some help.
Its really easy.
First of all, setup and initialize firebase in you project. Then make a function and create an instance of firestore like this
FirebaseFirestore firestore = FirebaseFirestore.instance;
Then make something called Collection reference:
CollectionReference users = await firestore.collection("users").get().then((querySnapshot) {
querySnapshot.docs.forEach((doc) {
print(doc["PhoneNumber"].toString())
});
This will grab every collection from Users, loop over them and then print out the document PhoneNumber to console. There is no way to just get a single document field from firestore. It might seem weird, but its quite useful at times. Right now, you have access to every document field of every user of your app.
I've been trying to implement live messaging in my application and I cannot seem to think of a convenient data structure inside Firestore. My current structure looks like this:
collection("conversations").document(id).collection("messages")
Each document holds two attributes user1 and user2 with nicknames of contributors to the conversation. Each document also owns a collection called messages which holds documents where each represents a single message sent with some info.
What I'm trying to do next is to check if the conversation already exists, if not then create it. The problem for me is write a correct query to find out if it exists.
My first idea was: create users array instead which holds nicknames of users and then simply query:
db.collection("conversations").whereField("users", in: ["username1", "username2"])
Problem with this is that it means "where users contains username1 OR username2", but I need it to contain "username1 AND username2".
I tried to be smart and chain the whereField function as following:
db.collection("conversations").whereField("users", arrayContains: "username1").whereField("users", arrayContains: "username2")
Turns out that you cannot use arrayContains more than once in a single query.
After that I came back to the structure as displayed on the screenshot with user1 and user2 and ran a new query:
db.collection("conversations").whereField("user1", isEqualTo: user).whereField("user2", isEqualTo: friend)
This query is ran in a function where user and friend are string parameters holding nicknames of both sender and receiver of the message we're currently sending. Imagine you are sending a message, user is always going to be your nickname and friend the receiver's one. The problem with the query is that you're nickname might be saved under user1 or user2 and receiver's nickname aswell. In either of those situations the conversation exists. How would I have to change the query since I don't know in an advance who will have which position in the query aswell as in Firestore. Running the last query that I included twice while switching user and friend parameter seems very unconvenient.
Any tips or solutions to progress in this problem will be much appreciated!
I've used the Real-Time Database with this setup:
->users
->uid
->name
->email
->other info
If I wanted to save the user data I would use my User class and then set the object in the database like this:
final FirebaseUser user = await FirebaseAuth.instance.currentUser();
FirebaseDatabase.instance.reference().child("kullanıcılar").child(user.uid).child("takip").set({"uid":"uid"});
I tried it and it works fine.
But how can I retrieve these values from the database? For instance, once I set a User object as shown above, I may want to retrieve the user's email. I don't mean getting the email through the sign-in provider. I want the email through the real-time database. I've tried working this out for a while now but the documentation isn't helping much. All it shows is to setup listeners in order to wait for changes to the data. But I'm not waiting for changes, I don't want a listener. I want to directly get the values in the database by using the keys in the JSON tree. Is this possible via the real-time database? If so, how can it be done because either the documentation doesn't explain it or I'm just not understanding it.Thanks.
You can retrieve the value once using .once(). Here's an example: https://github.com/flutter/plugins/blob/master/packages/firebase_database/example/lib/main.dart#L62
or better, with async/await:
Future<String> getEmail() async {
String result = (await FirebaseDatabase.instance.reference().child("path/to/user/record/email").once()).value;
print(result);
return result;
}
You can't retrieve the single value from firebase, it always return the DocumentSnapshot of the whole record. You can get a single record from user table by using user id like this:
getData() async {
final FirebaseUser user = await _firebaseAuth.currentUser();
return await FirebaseDatabase.instance.reference().child('user').equalTo(user.uid);
}
Get it like this:
getData().then((val){
print(val.email);
});