My below code is returning an empty list, even though it SHOULD return data corresponding to my data stored in my firestore database. Also to note: The otherUserId print statement is not getting printed. How can I fix this issue?
Future<List<String>> getChattingWith(String uid) async {
List<String> chattingWith = [];
try {
// create list of all users user is chatting with
final rooms = await FirebaseFirestore.instance
.collection('rooms')
.where('users', arrayContains: uid)
.get();
for (final room in rooms.docs) {
final users = room['users'] as Map<String, dynamic>;
final otherUserId = users['uid1'] == uid ? users['uid2'] : users['uid1'];
print("otherUserId999: $otherUserId");
chattingWith.add(otherUserId);
}
print("chattingWith: $chattingWith");
return chattingWith;
} catch (error) {
print("error: $error");
return [];
}
}
This part of your code does not match your data structure:
final rooms = await FirebaseFirestore.instance
.collection('rooms')
.where('users', arrayContains: uid)
.get();
Your users is a Map and not an array, so arrayContains won't work here. As said in my answer to your previous question, you have to use dot notation to test nested fields:
final rooms = await FirebaseFirestore.instance
.collection('rooms')
.where('users.uid1', isEqualTo: uid)
.where('users.uid2', isEqualTo: otherValue)
.get();
That 👆 is closest to what you tried in your previous question: Firestore conditional array query. It performs an AND condition on the uid1 and uid2 subfields of users.
If instead you want to get all rooms that the user is a participant in, you need an (additional) field that is an array with the UIDs of all participants.
participantUIDs: ["uid1", "uid2"]
Then you can do:
final rooms = await FirebaseFirestore.instance
.collection('rooms')
.where('participants', arrayContains: uid)
.get();
Related
This question already has answers here:
"The operator '[]' isn't defined" error when using .data[] in flutter firestore
(6 answers)
Closed 3 months ago.
I would like to recover data in my firebase database but it does not work.
void _userData() async {
DocumentReference documentReference = FirebaseFirestore.instance
.collection("Users")
.doc("axelduf2006#gmail.com");
documentReference.get().then((datasnapshot) {
data = datasnapshot.data;
return print("pseudo: ${data['pseudo']}");
});
}
my log console
I would like to know the value contained in pseudo in my database.
Change data with data() to get the Map<String, dynamic> of your document.
void _userData() async {
DocumentReference documentReference = FirebaseFirestore.instance
.collection("Users")
.doc("axelduf2006#gmail.com");
documentReference.get().then((datasnapshot) {
data = datasnapshot.data() as Map<String, dynamic>; // set it like this
return print("pseudo: ${data['pseudo']}");
});
}
Passing the data will pass the definition of Map<String, dynamic> Function ( () => Map<String, dynamic> ), not the actual Map<String, dynamic> of the document data.
In my orders list map Function I used another function that checks every order unique id from firebase database that if the id is exists on any document, if it's available then It should put the order item under that reference document if not then in It should create a new reference document and make a new list for that kind of order, but my when It runs inside the loop checking id query runs first and then runs the order placing part, so if fails the checking system
Here is the map function
orderNowList
.map(
(item) => {
orderRequestMaker(
item['title'],
item['product_ref_id'],
item['image_main'],
item['quantity'],
item['price_per_unit'],
item['total_price'],
item['delivery_charge'],
item['buyer_id'],
item['shop_id'],
item['shop_name'],
item['shop_image'],
uniqueId,
),
// removeRequestMaker(item['product_ref_id']),
},
)
.toList(),
Here is the order function
orderRequestMaker(
productName,
productId,
productImage,
productQuantity,
productUnitPrice,
productTotalPrice,
productDeliveryCharge,
buyerId,
shopId,
shopName,
shopImage,
uniqueId) async {
var orderRefId;
QuerySnapshot<Object> currentShopChecker = await FirebaseFirestore.instance
.collection('orders')
.where('ids', isEqualTo: uniqueId)
.get();//first it only runs this query loop limit times, then goes down, but I want
// to run query, get the result and do the rest of the operation
bool statusCheck = currentShopChecker.docs.length == 0;
statusCheck ? orderRefId = '' : orderRefId = currentShopChecker.docs[0].id;
DateTime presentTime = DateTime.now();
if (statusCheck) {
var orderRef = FirebaseFirestore.instance.collection('orders').doc();
orderRefId = orderRef.id;
orderRef.set({
'created_at': presentTime,
'buyer_name': buyerName,
'buyer_id': buyerId,
'ids': buyerId + shopId,
'buyer_image': buyerImage,
'shop_name': shopName,
'shop_id': shopId,
'shop_image': shopImage,
});
}
if (!statusCheck) {
await FirebaseFirestore.instance
.collection('orders')
.doc(orderRefId)
.update({
'created_at': presentTime,
});
}
await FirebaseFirestore.instance
.collection('orders')
.doc(orderRefId)
.collection('order_group')
.doc()
.set({
'created_at': presentTime,
'product_title': productName,
'product_id': productId,
'product_image': productImage,
'product_quantity': productQuantity,
'product_unit_price': productUnitPrice,
'product_total_price': productTotalPrice,
'product_delivery_charge':
productDeliveryCharge != null ? productDeliveryCharge : '',
'buyer_id': buyerId,
'shop_id': shopId,
'status': 'Order placed'
});
}
how to search through all documents for a specific field value
for eg: if i want the field: blood_group 'A+' from all documents and show me all documents which has 'A+' in it
https://i.stack.imgur.com/0IhT9.png
https://i.stack.imgur.com/4tkEG.png
source code
You can use the .where filter on the collection reference's query like below:
final QuerySnapshot querySnapshot = await FirebaseFirestore.instance.collection('users').where('blood_group', isEqualTo: 'A+').get();
final List<QueryDocumentSnapshot> documentSnapshotList = querySnapshot.docs;
for (QueryDocumentSnapshot snapshot in documentSnapshotList) {
print(snapshot.data());
}
You can use the .where option. Based on your firebase structure in the picture, you can use the following code, to get a list of all documents that satisfy your request.
Future<QuerySnapshot> bloodgroup (String bloodGroup) async {
return await FirebaseFirestore.instance.collection('Donation').where('blood_group', isEqualTo: bloodGroup).get();
}
void getDocs() async {
QuerySnapshot allResults = await bloodgroup('A+');
for (var item in allResults){
print(item.id); //this will print the id of all the documents which are A+.
}
}
This code is running fine with futurebuilder and i m getting a listview properly.
But i want to see into the documents n print the details in console. I m not getting any idea about how to do this with QuerySnapshot variable.
Future getP() async {
var firestore = Firestore.instance;
var q = await firestore.collection('place_list').getDocuments();
print(q.documents);
return q.documents;
}
I think I have to call it n wait for the responses then print them, can anyone guide me how to do it?
List<Map<String, dynamic>> list =
q.documents.map((DocumentSnapshot doc){
return doc.data;
}).toList();
print(list);
Though the answer is right the current firebase API has changed drastically now to access QuerySnapshot one can follow the below code.
FirebaseFirestore.instance
.collection('users')
.get()
.then((QuerySnapshot querySnapshot) => {
querySnapshot.docs.forEach((doc) {
print(doc["first_name"]);
});
});
And if you are using async/await then first you need to resolve the AsyncSnapshot and then work on it. If you like:
return FutureBuilder(
future: PropertyService(uid:userId).getUserProperties(),
builder: (BuildContext context, AsyncSnapshot<QuerySnapshot> snapshot){
if (snapshot.hasError) {
return Text("Something went wrong");
}
if (snapshot.connectionState == ConnectionState.done) {
snapshot.data.docs.forEach((element) {
Property property = Property.fromJson(element.data());
});
return Text("Demo Text");
}
return LoadingPage();
}
);
taken from url
//But I am not getting all the documents present in my firestore DB collection. The first 10 or so entries are getting printed in the console. //
I think that is standard behavior. If you have one million records it can't print everything in console. To check any particular set of documents you have to filter through where condition in query.
If you have still this problem, I hope this will help you.
This is how I get data from QuerySnapshot:
QuerySnapshot snapshot =
await userCollection.where("uid", isEqualTo: uid).get();
List<Object?> data = snapshot.docs.map((e) {
return e.data();
}).toList();
Map<dynamic, dynamic> userData = data[0] as Map;
print(userData["email"]);
Or you can easily get data by:
QuerySnapshot querySnapshot =
await userCollection.where("uid", isEqualTo: uid).get();
print(querySnapshot.docs[0)['fieldName']);
I have a collection of following;
I want to return every company in ascending order by companyName and this is how I'm trying;
QuerySnapshot usersComp = await _firestore
.collection('companies')
.where('belongsTo', isEqualTo: curruser.uid)
.orderBy({
'properties': {'companyName'}
}, descending: false).getDocuments();
Code doesn't give any errors but it also doesn't return any value as well. The statement without orderBy works fine.
How can I write a this orderBy in a working way?
edit
This is the whole getCompanies function in FirebaseCrud:
Future<List<Company>> getCompanies() async {
FirebaseUser curruser = await _authService.getCurrentUser();
DocumentSnapshot userSnapshot = await Firestore.instance
.collection('users')
.document(curruser.uid)
.get();
List partners = userSnapshot.data['partners'];
print('partners');
print(partners[0]);
QuerySnapshot usersComp = await _firestore
.collection('companies')
.where('belongsTo', isEqualTo: curruser.uid)
//.orderBy('properties.companyName', descending: false) // code works fine without this line but not as expected
.getDocuments();
List<Company> companies = new List<Company>();
usersComp.documents.forEach((f) {
int indexOfthis = usersComp.documents.indexOf(f);
companies.add(new Company(
uid: partners[indexOfthis],
companyName: f.data['properties']['companyName'],
address: f.data['properties']['address'],
paymentBalance: f.data['currentPaymentBalance'],
revenueBalance: f.data['currentRevenueBalance'],
personOne: new Person(
phoneNumber: f.data['properties']['personOne']['phoneNumber'],
nameAndSurname: f.data['properties']['personOne']
['nameAndSurname']),
personTwo: new Person(
phoneNumber: f.data['properties']['personTwo']['phoneNumber'],
nameAndSurname: f.data['properties']['personTwo']
['nameAndSurname']),
));
});
return companies;
}
Use dot notation to reference properties of objects to use for sorting.
_firestore
.collection('companies')
.where('belongsTo', isEqualTo: curruser.uid)
.orderBy('properties.companyName'),
descending: false)
I created a collection with a few documents, each have a top-level field and a nested field. If I then run a query over it like this:
Firestore.instance.collection("59739861")
.where("location", isEqualTo: "Bay Area")
.orderBy("properties.companyName", descending: false)
.getDocuments().then((querySnapshot) {
print("Got ${querySnapshot.documents.length} documents");
querySnapshot.documents.forEach((doc) {
print("${doc.documentID}: ${doc.data['properties']}");
});
});
I have added these three documents in my database:
location: "Bay Area", properties.companyName: "Google"
location: "Bay Area", properties.companyName: "Facebook"
location: "Seattle", properties.companyName: "Microsoft"
With the above query, I get the following output printed:
flutter: KJDLLam4xvCJEyc7Gmnh: {companyName: Facebook}
flutter: TMmrOiKTYQWFBmJpughg: {companyName: Google}
I have no idea why you're getting different output.
Just in case it matters, I run the app in an iOS simulator and use this version of the Firestore plugin:
cloud_firestore: ^0.13.0+1