flutter firebase how do I get all the children of a node - firebase

I am not very familiar with using dart and firebase and I was wondering how I could get all the children of a certain node and how I could check if a node exists

Something like this should you get the list of users:
static Future<int> getUserAmount() async {
final response = await FirebaseDatabase.instance
.reference()
.child("Users")
.once();
var users = [];
reponse.value.forEach((v) => users.add(v));
print(users);
return users.length;
}
You can check with users what you need to check and then return a result;

If you want only the name of the parentes of the example bellow:
https://i.stack.imgur.com/NjxbJ.png
I'd use the code of Günter Zöchbauer with a little modification. The result will be: user = [A,B,C,D,E,LIVRE] with 5 length size.
Future getUserAmount() async
{
final database = await FirebaseDatabase.instance
.reference()
.child("CHILD1/ana/exercicios/")
.once();
List <String> users = [];
database.value.forEach((key,values) => users.add(key));
print(users);
print(users.length);
}

Related

Flutter firebase check email exist inside firestore collection

I need to just check if user email exist in user collection or not. Right now I am doing like this
var check = await FirebaseFirestore.instance.collection('users')
.where('email', isEqualTo: userData['email']).snapshots();
But when I print check its showing
Instance of '_MapStream<QuerySnapshotPlatform, QuerySnapshot<Map<String, dynamic>>>'
How can I check that email exist in that collection or not ? Thanks 😊
Your check variable is a QuerySnapshot object, while you seem to want it to be a boolean that indicates whether the query had any results.
To get that:
var query = FirebaseFirestore.instance.collection('users')
.where('email', isEqualTo: userData['email']).limit(1);
var snapshot = await query.snapshots();
var check = query.size > 0;
Note that I also added a limit(1) to the query, since you never need to read more than one document to determine if any matches exist.
you can try or take reference form this method let me know if this solves your problem
static Future<bool> emailCheck(String email) async {
bool result = false;
QuerySnapshot snapshot = await
FirebaseFirestore.instance.collection('Users').get();
snapshot.docs.forEach((f) {
if (f['email'] ==email) {
result =true;
}
});
return result;
}

Flutter Firestore Update Where

I'm trying to run a query that retrieves a single row given a where clause and updates it. I understand that Firebase doesn't support an UpdateWhere operations so I'm trying to use a Transaction instead.
I'm having difficulty making it work, maybe I'm too used to sql dbs... Here's my broken code
try {
final whereQuery = _db
.doc(userPath(user))
.collection("someInnerCollection")
.where("active", isEqualTo: true)
.limit(1);
await _db.runTransaction((transaction) async {
final entry = await transaction.get(whereQuery); // This doesn't compile as .get doesn't take in a query
await transaction.update(entry, {
"someValue": "newValue",
});
});
} catch (e) {
...
}
From the test I’ve made, I would suggest the following to achieve what you mention:
Based on the following answer:
As you can see from the API documentation, where() returns a Query object. It's not a DocumentReference.
Even if you think that a query will only return one document, you still have to write code to deal with the fact that it could return zero or more documents in a QuerySnapshot object. I suggest reviewing the documentation on queries to see examples.
After doing the query consult, you have to get the DocumentReference for that given result.
Then, you can use that reference to update the field inside a Batched writes
try {
final post = await firestore
.collection('someInnerCollection')
.where('active', isEqualTo: true)
.limit(1)
.get()
.then((QuerySnapshot snapshot) {
//Here we get the document reference and return to the post variable.
return snapshot.docs[0].reference;
});
var batch = firestore.batch();
//Updates the field value, using post as document reference
batch.update(post, { 'someValue': 'newValue' });
batch.commit();
} catch (e) {
print(e);
}
You are passing the DocumentSnapshot back in the update() operation instead of DocumentReference itself. Try refactoring the like this:
final docRefToUpdate = _db.collection("colName").doc("docId");
await _db.runTransaction((transaction) async {
final entry = await transaction.get() // <-- DocRef of document to update in get() here
await transaction.update(docRefToUpdate, {
// Pass the DocumentReference here ^^
"someValue": "newValue",
});
});
You can use a collection reference and then update single fields using .update().
final CollectionReference collectionReference = FirebaseFirestore.instance.collection('users');
await collectionReference.doc(user.uid).collection('yourNewCollection').doc('yourDocumentInsideNestedCollection').update({
'singleField': 'whatever you want,
});
Same code using "where"
collectionReference.doc(user.uid).collection('yourNewCollection').doc().where('singleField', isEqualTo: yourValue).update({
'singleField': 'whatever you want,
});

How to retrieve value of child data from firebase DB?

I am trying to grab the children data from a certain movie title in a database, but I can only get an output of "Instance of Datasnapshot."
Here is the setup of the DB with the highlighted information I am trying to store in a list:
I tried using the following code with no success:
Future<List<String>> getMovieDetails(String movieName) async {
DataSnapshot movies = await DBRef.child("Movies").child(movieName).once().then((DataSnapshot datasnapshot)
{
print(datasnapshot.value.toString());
});
var moviesMap = Map<String, dynamic>.from(movies.value);
List<String> moviesList = [];
moviesMap.forEach((key, value){
moviesList.add(key);
print('My-Key $key');
print('Movie List: $moviesList');
});
return moviesList;
}
Note: I am passing the selected movie name so I only grab the child information from the movie the user selects. This portion is correctly, if the user clicks on the list tile of Batman, the title will be passed to this getMovieDetails() function.
Try the following:
Future<List<String>> getMovieDetails(String movieName) async {
DataSnapshot movies = await FirebaseDatabase.instance
.reference()
.child("Movies")
.child(movieName)
.once();
var moviesMap = Map<String, dynamic>.from(movies.value);
List<String> moviesList = [];
moviesMap.forEach((key, value) {
moviesList.add(value);
print('My-Key $key');
print('My-Value $value');
});
return moviesList;
}
}
You dont have to use then() since you are using await. Also when you call this method, you need to do for example:
await getMovieDetails("Batman");
I will make the above answer as correct, but the biggest issue was when I did:
moviesList.add(key)
When it should be:
moviesList.add(value)

Retrieve Document content from Firebase in Flutter

I'm trying to retrieve user data from a Firebase Collection.
This is what it looks like:
This is the method I wrote to get the data:
static String getUserData(creatorId, keyword) {
var documentName = Firestore.instance
.collection('users')
.document(creatorId)
.get()
.then((DocumentSnapshot) {
String data = (DocumentSnapshot.data['$keyword'].toString());
return data;
});
}
The method only returns null. If I print the String in the Method it works. How can I return the String?
Help would be greatly appreciated.
Cheers Paul
You need to use async and await to be able to wait for the data to be fully retrieved and then you can return the data.
The async and await keywords provide a declarative way to define asynchronous functions and use their results.
For example:
Future<String> getUserData(creatorId, keyword) async {
var documentName = await Firestore.instance
.collection('users')
.document(creatorId)
.get()
.then((DocumentSnapshot) {
String data = (DocumentSnapshot.data['$keyword'].toString());
return data;
});
}
And then you since getUserData returns a Future, you can use the await keyword to call it:
await getUserData(id, key);
https://dart.dev/codelabs/async-await#working-with-futures-async-and-await

How do I get the surrounding data related to my userId using flutter and firebase

While using flutter I am able to successfully get the UserId, however I want to be able get more user data (using the UserId)
Surrounding Information:
With the userId how would I go about printing the users; name bio, membership... etc?
Since you are using Realtime Database, then to get the other data, you can do the following:
db = FirebaseDatabase.instance.reference().child("Users");
db.once().then((DataSnapshot snapshot){
Map<dynamic, dynamic> values = snapshot.value;
values.forEach((key,values) {
print(values);
print(values["name"]);
});
});
First add a reference to node Users then use the forEach method to iterate inside the retrieved Map and retrieve the other values.
Try like this :
Future<dynamic> getWeightinKeg() async {
final DocumentReference document = Firestore.instance.collection('you_collection_name').document(user_id);
await document.get().then<dynamic>(( DocumentSnapshot snapshot) async {
final dynamic data = snapshot.data;
print(data['name'].toString())
//Do whatever you want to do with data here.
});
}
getUsers() async {
//here fbPath is reference to your users path
fbPath.once().then((user){
if(user.value !=null){
Map.from(user.value).forEach((k,v){
//here users is List<Map>
setState((){
users.add(v);
});
}
}
});
}
//Or
getUsers() async {
//here fbPath is reference to your users path
//and userListener is StreamSubscription
userListener = fbPath.onChildAdded.listen((user){
//here users is List<Map>
setState((){
users.add(Map.from(user.snapshot.value));
});
});
}
//and cancel in dispose method by calling
userListener.cancel();

Resources