How can i manually add document-fields into local QueryDocumentSnapshot List - flutter

i have the following list
List <QueryDocumentSnapshot> globalVideosUrls = [] ;
for example if we use the following
FirebaseFirestore.instance.collection('users')
.limit(1).get().then((value){
globalVideosUrls.add(value)
});
it will add as expected
but what if i want to manually add the following data into globalVideosUrls
document id
00dcb026-3163-4ca0-859e
fields
'videoType':'peace'
'url':'url'
.
globalVideosUrls.add(????)

You have to replace the type "QueryDocumentSnapshot" with QuerySnapshot and then you will get multiple docs and with there data also try this If any questions then ask.
thanks🙏.
List<QuerySnapshot> globalVideosUrls = [];
List<String> videoUrlList = [];
await FirebaseFirestore.instance
.collection('users')
.get()
.then((value) {
globalVideosUrls.add(value);
});
globalVideosUrls.forEach((element) {
element.docs.forEach((docELe) {
print("data:- ${docELe.data()}");
Map map = docELe.data() as Map;
videoUrlList.add(map['url']);
});
});

Related

Flutter Populating List<String> using for loop

I want to get all the document IDs in my firebase and store it in List but I'm only getting one of the documents. Here is my execution
PrtSc
my code
Future saveUserCart(User currentUser) async
{
List<String> IDs = [];
Future getDocs() async {
QuerySnapshot querySnapshot = await FirebaseFirestore.instance
.collection('users')
.doc(currentUser.uid)
.collection("userCart").get();
for (int i = 0; i < querySnapshot.docs.length; i++) {
var itemIDs = querySnapshot.docs[i];
print(itemIDs.id);
IDs = [itemIDs.id];
}
print(IDs);
}
getDocs();
}
Fix my problem and learn something
Try IDs.add(itemIDs.id); instead of IDs=[itemIDs.id];
Instead of adding the code in question is creating a new list and assigning it to the last id. When we use add method we can get all ids from the documents.
Future saveUserCart(User currentUser) async
{
List<String> IDs = [];
Future getDocs() async {
QuerySnapshot querySnapshot = await FirebaseFirestore.instance
.collection('users')
.doc(currentUser.uid)
.collection("userCart").get();
for (int i = 0; i < querySnapshot.docs.length; i++) {
var itemIDs = querySnapshot.docs[i];
print(itemIDs.id);
IDs.add(itemIDs.id);
}
print(IDs);
}
getDocs();
}
It's just Example,
you can use base on your requirements. For gettings "ID" you don't need to use for loop, use "map" functions.
var data = [{'key':'abc', 'id':1},{ 'key': 'xyz', 'id': 2}];
var mapData = data.map((res) => res['id']);
print("mapData => ${mapData.toList()}");
Expected Output,
mapData => [1, 2]
Maybe, it will help you.

How to use Array contains in the same array fields in firebase for flutter

I have a chat collection.
each document has an array with two user id's.
my goal is to get the chat that has both user sys id's
I tried running the following but I got an error because we cant use two 'arrayContains' in one query.
Is there any way to perform such query?
here is an image of the data structure
Future getChat({required List userIdsArr}) async {
var docId = '';
userIdsArr.sort((a, b) {
return a.compareTo(b);
});
var filter1 = userIdsArr[0];
var filter2 = userIdsArr[1];
await chat
.where(userIdsArrayColumn, arrayContains: userIdsArr[0])
.where(userIdsArrayColumn, arrayContains: userIdsArr[1])
.get()
.then((value) {
value.docs.forEach((element) {
docId = element.id;
});
});
return docId;
}
the goal is to get the chat that pertains to the users being passed in userIdsArr
this seems to work, is there a better way of doing this?
Future getChat({required List userIdsArr}) async {
var docId = '';
userIdsArr.sort((a, b) {
return a.compareTo(b);
});
await chat
.where(userIdsArrayColumn, arrayContains: userIdsArr[0])
// .where(userIdsArrayColumn, arrayContains: userIdsArr[1])
.get()
.then((value) {
value.docs.forEach((element) {
if (element[userIdsArrayColumn].contains(userIdsArr[1])) {
log('match found!');
docId = element.id;
}
});
});
return docId;
}
A query can only contain a single array-contains query.
To allow your query, you'll want to add an additional field to the document where you keep the pair of UIDs in a predictable (e.g. alphabetical) order. With such a field you can then use a query such as:
where("concatenated_uids", isEqualTo: userIdsArr[0]+"_"+ userIdsArr[1])

How to loop through Instance of '_MapStream<QuerySnapshotPlatform, QuerySnapshot<Map<String, dynamic>>>'?

static List categoryList() {
final categorySnapshots = FirebaseFirestore.instance
.collection('categories')
.orderBy('name')
.snapshots();
List categories = [];
categorySnapshots.map((snapshot) => snapshot.docs.map((doc) {
print(snapshot.toString());
categories.add(doc.data()['name']);
}));
print(categories);
return categories;
}
Categories is empty.
How to populate it with the data from snapshots?
I added a new collection called "school", there're two items added inside the document.
void getMessagesTest() async{
QuerySnapshot querySnapshot = await _firestore.collection('school').orderBy('age',descending: true).get();
final allData = querySnapshot.docs.map((doc) => doc.data()).toList();
print(allData);
}
I used my code, and it works. Could you please remove ".where" and try it again?
You could chain where and orderBy together. Please see my code below. Reference link => Using Where and Order by different fields in Firestore query
void getMessagesTest() async{
QuerySnapshot querySnapshot = await _firestore.collection('school').orderBy('age', descending: true).where('age', isGreaterThan: 17).get();
final allData = querySnapshot.docs.map((doc) => doc.data()).toList();
print(allData);
}
Using the below code might help
you can convert the snapshot to Map<String,dynamic> by using the following function:
static Post fromSnap(DocumentSnapshot snap) {
var snapshot = snap.data() as Map<String, dynamic>;
}

flutterfire where and orderby not return data

i have implemented this code for retrieving the messages of this room.
final messagesProvider = StreamProvider((ref) {
FirebaseFirestore db = FirebaseFirestore.instance;
var room = ref.watch(roomIdProvider);
print('room updated');
print('room is '+room);
final docRef = db
.collection("messages")
.where("chat_room_id",isEqualTo: room)
// .orderBy('created_at')
// .orderBy('created_at',descending: true)
;
print(docRef.orderBy("created_at").snapshots());
return docRef.snapshots();
});
i want to sort the data and have tried these two lines separately but not worked for me
.orderBy('created_at')
.orderBy('created_at',descending: true)
where created at is a timestamp field.
I added a new collection called "school", there're two items added inside the document.
I used my code, and it works. Could you please remove ".where" and try it again?
void getMessagesTest() async{
QuerySnapshot querySnapshot = await _firestore.collection('school').orderBy('age',descending: true).get();
final allData = querySnapshot.docs.map((doc) => doc.data()).toList();
print(allData);
}
Updated 20220616:
Updated 20220618:
Yes, you could chain where and orderBy together. Please see my code below.
Reference link => Using Where and Order by different fields in Firestore query
void getMessagesTest() async{
QuerySnapshot querySnapshot = await _firestore.collection('school').orderBy('age', descending: true).where('age', isGreaterThan: 17).get();
final allData = querySnapshot.docs.map((doc) => doc.data()).toList();
print(allData);
}

How to convert map into array to firestore? flutter

I have a users id I want to add it to firestore, like this
['GEcuHm3ICpWlEzfq1Z2tAjI2LII3', 'GEcuHm3ICpWlEzfq1Z2tAjI2LII3' ...]
I tried multiple ways but it didn't work
List membersListUid = [];
Future createGroup() async{
GroupRoomModel newGroup = GroupRoomModel(
groupName: groupName.text,
groupRoomId: uuid.v1(),
owner: userModel.uid,
membersList: controller.membersList,
membersListUid: controller.membersListUid.cast() // <---
);
}
...
Future createGroupFunc() async{
GroupRoomModel newGroup = GroupRoomModel(
groupName: groupName.text,
groupRoomId: uuid.v1(),
owner: userModel.uid,
membersList: controller.membersList,
membersListUid: controller.membersListUid.map((e)=> e).toList() //<---
);
...
Maybe this helps to understand the code
//Controller class
Map<String, dynamic>? userMap;
onSearch() async {
await _fireStore
.collection('users')
.where("email", isEqualTo: searchedMembers.text)
.get()
.then((value) {
userMap = value.docs[0].data();
});
update();
}
membersListUid.add({
"uid": userMap!['uid']
});
It's still gives me map within array.
THE PROBLEM:
membersListUid is a List of Maps. That is why you get an array of Maps in your database.
You need to get the actual value of the uid from each Map by using the uid key to get the value from the map.
THE SOLUTION:
Update this line:
membersListUid: controller.membersListUid.map((e)=> e).toList()
to this below:
controller.membersListUid.map((e)=> (e as Map<String, dynamic>)['uid']).toList()