How to read subcollection from flutter firestore. I am using cloud_firestore. I am successfully adding data into firestore but couldn't retrieve it(tried and failed).
I want to retrieve subCollection called product Firestore collection
I tried this I don't have the document ID Because it generated automatically from firestore :
Stream<QuerySnapshot> loadorderdetails(String uid) {
return FirebaseFirestore.instance
.collection('Users/$userid/Orders')
.doc()
.collection("Products")
.where('uid', isEqualTo: uid)
.snapshots();
}
You should try this
FirebaseFirestore.instance.collection("Users/$userid/Orders ").get().then((querySnapshot) {
querySnapshot.docs.forEach((result) {
FirebaseFirestore.instance
.collection("Users/$userid/Orders")
.doc(result.id)
.get()
.then((querySnapshot) {
//print data
});
});
});
});
Related
So I am trying to make a chat app with cloud Firestore and I don't how to delete a document by timestamp.
This is currently how I delete a document.but when I tried it deletes all the document:
onLongPress: () async {
await FirebaseFirestore.instance
.collection('messages')
.doc(
groupChatId)
.collection(
groupChatId)
.orderBy("timestamp",descending: true).get().then((value) => {
for(DocumentSnapshot ds in value.docs){
ds.reference.delete()
}
});
},
try this code:
await FirebaseFirestore.instance
.collection('messages')
.doc(
groupChatId)
.collection(
groupChatId)
.where("timestamp", isLessThan: DateTime.now().microsecondsSinceEpoch-TheNumberOfMicrosencundenTheDocumentCanBeOld).get().then((value) => {
for(DocumentSnapshot ds in value.docs){
ds.reference.delete()
}
});
I want to build a contactScreen for my flutter app. Therefor I have to download an array from Firebase. I am just able to download directly into a listView in flutter and get stuck while coding. Heres my code:
var currentUser = FirebaseAuth.instance.currentUser!.uid;
var contacts;
getUserData() async {
var userData = await FirebaseFirestore.instance
.collection('users')
.where('uid', isEqualTo: currentUser)
.get();
contacts = userData['contacs']; //heres the error
}
At first I want to initialize the currentUser's UID and then get the currentUser's contacts array from firebase. Therefor I build the getUserData() method to download the User and then initialize his contacts array.
The last step doesn't work in Flutter, I can't access the contacts array. Is the way I want to get the data correct?
You're at the very least missing an await before the get() call:
var userData = await FirebaseFirestore.instance
.collection('users')
.where('uid', isEqualTo: FirebaseAuth.instance.currentUser!.uid)
.get();
Without await your userData is of type Future<QuerySnapshot<Map<String, dynamic>>> as you get in the error message. By using await, its type will become QuerySnapshot<Map<String, dynamic>>.
you need to call await or use FutureBuilder
like this
FutureBuilder(
future: FirebaseFirestore.instance
.collection('users')
.where('uid', isEqualTo: FirebaseAuth.instance.currentUser!.uid)
.get(),
builder: (context, snapshot) {
if (snapshot.hasData) {
return Column(
children: [Text(snapshot.data['name'])], //error here
);
}
return Loading();
},
)
I have two attributes in my eventClick table eventID and userID so what I am trying to do is if eventID and userID normally exists then show You have already clicked if not then make an entry of the click. I thought of using two clause and merging it but that just resulted in insertion of the values.
I am trying using the below code
final checkSnapshot = FirebaseFirestore.instance
.collection('eventClick')
.where('eventID', isEqualTo: eventID)
.where('userID', isEqualTo: userID)
.snapshots();
I want the working to be like
if (checkSnapshot.exists) {
print('already exists');
} else {
FirebaseFirestore.instance.collection('eventClick').add({
'eventID': eventID,
'eventName': eventName,
'eventImageUrl': eventImageUrl,
'userID': userID
});
}
Can you try using .get() ? That should return a QuerySnapshot which has a 'size' property. If 0, that means no such document exists.
FirebaseFirestore.instance
.collection('eventClick')
.where('eventID', isEqualTo: eventID)
.where('userID', isEqualTo: userID)
.get()
.then((checkSnapshot) {
print(checkSnapshot.docs[0]);
if (checkSnapshot.size > 0) {
print("Already Exists");
} else {
//add the document
}
});
FirebaseFirestore.instance
.collection('task')
.where('usergroup', isEqualTo: 'software')
.where('userid', isEqualTo: 'ep434334')
.snapshots(),
FirebaseFirestore _firestore = FirebaseFirestore.instance;
CollectionReference _userRef = FirebaseFirestore.instance.collection('users');
Future getFriends() async {
List<Map> info = [];
await _firestore
.collection('friends')
.doc('lUb3VEzLQsqxxEhwO3nU')
.collection('friends')
.get()
.then((QuerySnapshot querySnapshot) {
querySnapshot.docs.forEach((element) async {
print("hello " + element.id.toString());
await _userRef.doc(element.id).get().then((value) {
print("lalala" + value.data().toString());
info.add(value.data());
});
});
});
print(info.toString());
}
I am trying to build a Flutter application using Firestore.My firestore has two collections namely users and friends.Collection users contains documents with locations,names and Collection friends contains documents which each have a subcollection friends that store the Unique IDs of "users" who are friends. This is the output when I execute the above function
I/flutter ( 7773): hello eyHBWGrNoxSMe8cQUqWC
I/flutter ( 7773): []
I/flutter ( 7773): lalala{loc: Instance of 'GeoPoint', dname: hamza ansari}
PROBLEM: The data is not getting stored into the list 'info'. Any help with this would be appreciated :D
.Here is a photo of the friends collection.
And here is a photo of the users collection.
Would really love it if someone could help me out here :)
You can access the documents by snapshot.data.documents then you can get document Id like this
var doc= snapshot.data.documents;
var docId=doc[index].documentID
FirebaseFirestore.instance
.collection('dishes')
.doc(docId)
.collection('ingredients')
.snapshots(),
i think the problem is that you are simply not returning anything in your Future.
try this
FirebaseFirestore _firestore = FirebaseFirestore.instance;
CollectionReference _userRef = FirebaseFirestore.instance.collection('users');
Future getFriends() async {
List<Map> info = [];
await _firestore
.collection('friends')
.doc('lUb3VEzLQsqxxEhwO3nU')
.collection('friends')
.get()
.then((QuerySnapshot querySnapshot) {
querySnapshot.docs.forEach((element) async {
print("hello " + element.id.toString());
await _userRef.doc(element.id).get().then((value) {
print("lalala" + value.data().toString());
info.add(value.data());
});
});
});
return info ;
}
The problem seems to be with the conversion of the subcollection to a list. Try the following:
FirebaseFirestore _firestore = FirebaseFirestore.instance;
CollectionReference _userRef = FirebaseFirestore.instance.collection('users');
Future getFriends() async {
List<Map> info = [];
await _firestore
.collection('friends')
.doc('lUb3VEzLQsqxxEhwO3nU')
.collection('friends')
.get()
.then((QuerySnapshot querySnapshot) {
querySnapshot.docs.forEach((element) async {
print("hello " + element.id.toString());
await _userRef.doc(element.id).get().then((value) {
print("lalala" + value.data().toString());
info.add(Map(Map.fromMap(value.data())));
});
});
});
print(info.toString());
}
I have tasks subcollection for every user, How can I delete tasks ,
CollectionReference users = FirebaseFirestore.instance.collection('users');
final FirebaseAuth _auth = FirebaseAuth.instance;
Future<void> deleteTask() {
return users
.doc(user.uid)
.collection('Tasks').delete() ?? ??
.then((value) => print("Tasks Deleted"))
.catchError((error) => print("Failed to delete task: $error"));
}
To delete all documents in collection or subcollection with Cloud Firestore, you can use the delete method iterating on a DocumentReference:
CollectionReference users = FirebaseFirestore.instance.collection('users');
Future<void> deleteAllTaskDocs() {
return users
.doc(user.uid)
.collection('Tasks')
.get()
.then((QuerySnapshot querySnapshot) {
querySnapshot.docs.forEach((doc) {
doc.reference.delete();
});
});
}
Keep in mind that:
There is no operation that atomically deletes a collection.
Deleting a document does not delete the documents in its subcollections.
If your documents have dynamic subcollections, it can be hard to know what data to delete for a given path.
Deleting a collection of more than 500 documents requires multiple batched write operations or hundreds of single deletes.