Flutter: Get Firebase Database reference child all data - firebase

I have a firebase database child which content is like below:
How to retrieve this in flutter?
My Current code:
static Future<Query> queryUsers() async{
return FirebaseDatabase.instance
.reference()
.child("zoom_users")
.orderByChild('name');
}
queryUsers().then((query){
query.once().then((snapshot){
//Now how to retrive this snapshot? It's value data giving a json
});
});

To retrieve the data try the following:
db = FirebaseDatabase.instance.reference().child("zoom_users");
db.once().then((DataSnapshot snapshot){
Map<dynamic, dynamic> values = snapshot.value;
values.forEach((key,values) {
print(values["name"]);
});
});
Here first you add the reference at child zoom_users, then since value returns data['value'] you are able to assign it to Map<dynamic, dynamic> and then you loop inside the map using forEach and retrieve the values, example name.
Check this:
https://api.dartlang.org/stable/2.0.0/dart-core/Map/operator_get.html
Flutter: The method forEach isn't defined for the class DataSnapshot

query.once().then((snapshot){
var result = data.value.values as Iterable;
for(var item in result) {
print(item);
}
});
or with async that you already use
var snapshot = await query.once();
var result = snapshot.value.values as Iterable;
for(var item in result) {
print(item);
}

Related

how to add new data to existing list in firebase flutter

here is the firebase console
when I tried to add new value using this code
FirebaseFirestore.instance.collection('userCollection').doc(user!.uid).set({
'purchased-id': [oldPurcasedID]
}, SetOptions(merge: true));
and here is the getPurchaseID function
getPurchasedID() async {
DocumentSnapshot pathData = await FirebaseFirestore.instance
.collection('userCollection')
.doc(user!.uid)
.get();
if (pathData.exists) {
Map<String, dynamic>? fetchDoc = pathData.data() as Map<String, dynamic>?;
final purchasedIdMap = await fetchDoc?['purchased-id'];
print('purchased map value : $purchasedIdMap');
return purchasedIdMap;
}
return [];
}
it is replacing the '0'th list value,
how do I add new list under this
I also tried SetOptions(merge: true));. but this didn't help
Use update instead set, which overwrites a document.

Pass variable from function to late stream flutter

I am trying to get getGrupoFav to pass it as a variable to the late Stream<QuerySnapshot> task..., I tried with get but I did not know how to do it and I did not find a solution, I do not know if there is a better way to do it.
the error says
"Try correcting the name to the name of an existing getter, or defining a getter or field named 'getGrupoFav'.
.doc(getGrupoFav)
"
_fetch() async {
final String? userID = FirebaseAuth.instance.currentUser?.uid;
await FirebaseFirestore.instance
.collection("usuarios")
.doc("$userID")
.get()
.then((value) {
String getGrupoFav = value.data()!["grupofav"];
return getGrupoFav;
}).catchError((e) {
print(e);
});
}
late Stream<QuerySnapshot> task = FirebaseFirestore.instance
.collection("grupos")
.doc(getGrupoFav)
.collection("tareas")
.snapshots();
You should build your code something around like below and for the Flutter code syntax please have a look at this documentation
var collection = FirebaseFirestore.instance.collection('usarios');
var userID = FirebaseAuth.instance.currentUser?.uid;
var docSnapshot = await collection.doc(userID).get();
if (docSnapshot.exists) {
Map<String, dynamic> data = docSnapshot.data()!;
var name = data['name'];
}
Then you pass this variable to the document like,
var task = FirebaseFirestore.instance .collection("grupos") .doc(name).snapshots()

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)

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();

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

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);
}

Resources