Pass variable from function to late stream flutter - firebase

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

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.

How to get a single document data from Cloud_Firestore to my variable?

I have been trying to get a single data from Firestore. But I can't.
void _onPressed() async{
var firebaseUser = await FirebaseAuth.instance.currentUser();
var userData;
firestoreInstance.collection("users").document(firebaseUser.uid).get().then((value){
setState(){
userData = value.data
}
print('Value data = ${value.data}');
});
print('UserData = ${userData}');
}
Result:
Value data = { some data some data}
UserData = null
Why is my userData null? How do I solve this? I'm looking forward to hearing from you.
get() is asynchronous and returns immediately before the query is complete. then() is also asynchronous (as well as anything that returns a Future). Use await instead of then to pause your code until a result is available.
var snapshot = firestoreInstance.collection("users").document(firebaseUser.uid).get()
var userData = snapshot.data
print('UserData = ${userData}')
You have to do the following:
void _onPressed() async{
var userData;
var firebaseUser = await FirebaseAuth.instance.currentUser();
var result = await firestoreInstance.collection("users").document(firebaseUser.uid).get();
setState((){
userData = result.data;
});
}
Since get() is asynchronous then use await to wait for the result, after that you can call setState() which will rebuild the layout with the new data.
If you are using cloud_firestore: 0.14.0+ then use this code:
void _onPressed() async{
var userData;
var firebaseUser = FirebaseAuth.instance.currentUser;
var result = await FirebaseFirestore.instance.collection("users").doc(firebaseUser.uid).get();
setState((){
userData = result.data();
});
}
Since You put this line outside the then function.
print('UserData = ${userData}');
firestoreInstance.collection("users").document(firebaseUser.uid).get().then((value){
setState(){
userData = value.data
}
print('Value data = ${value.data}');
});
print('UserData = ${userData}'); //Since this line is outside the then function.
// This line will be execute before the then function(then function will execute after getting the data from firebase)

Flutter & Firebase: Is there a way I can return a specific field from firebase to a function?

users>user Id then:
My aim is to return the user's key from the document and then be able to use that key in other functions.
getUsersKey() async {
final uid = await getCurrentUser();
Firestore.instance.collection('users').document(uid).get();
// Then I want to return the userKey feild
}
You can write the code below:
Future<void> getUsersKey() async {
final uid = await getCurrentUser();
DocumentSnapshot snapshot =
await Firestore.instance.collection('users').document(uid).get();
userKey = snapshot.data['userKey'] //you can get any field value you want by writing the exact fieldName in the data[fieldName]
}

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

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