How to get particular data from List<Object> in flutter - flutter

Im getting data using querysnapshot in my flutter project.
But can not print all the name from the List.
My code :
var collectionRef = FirebaseFirestore.instance.collection("users") .where("role",
isEqualTo: "Student");
Future<void> getData() async {
// Get docs from collection reference
QuerySnapshot querySnapshot = await collectionRef.get();
// Get data from docs and convert map to List
final allData = querySnapshot.docs.map((doc) => doc.data()).toList();
print(allData.runtimeType);
for (var data in allData){
print(data['name']);
}
response from firebase

Related

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

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

How to read Firestore field value in flutter?

I want to get field value.
my code is..
void _checkNumner(String number) async {
final userRef = firestore.collection('users');
var documentSnapshot =
await userRef.where("number", isEqualTo: true).get().then((num) {
QuerySnapshot<Map<String, dynamic>> number = num;
print(number);
print("test");
});
print(documentSnapshot);
}
but my console is
how I get field number?
I want to load number values ​​in all docs.
I'm so beginer. T.T
Please reply from the masters
Thank you
Firebase firestore is a NoSQL, document-oriented database. User Data is stored in documents which are organized into collection , i.e collection contains list of document. In simpler words we can say QuerySnapshot contains/provide group of DocumentSnapshot. more about firestore data model
Collection --> QuerySnapshot --> Group of DocumentSnapshot
Document --> DocumentSnapshot
1) Fetch from collection - QuerySnapshot
Here we'll get list of DocumentSnapshots, we can filter by using where commad
Future<void> checkNumber(int number) async {
final QuerySnapshot snapshot = await FirebaseFirestore.instance
.collection('users')
.where("number", isEqualTo: number)
.get();
snapshot.docs.isEmpty
? {
//TODO: your code here
debugPrint("no data found")
}
: {
for (DocumentSnapshot element in snapshot.docs)
{
//TODO: your code here
debugPrint("number is: ${element['number']}"),
debugPrint("name is: ${element['name']}"),
}
};
}
1) Fetch from document - DocumentSnapshot
To fetch data from document we require documentId, and we get a single documentSnapshot instead of multiple like in above way.
Future<void> checkNumberWithDocId() async {
const String docId = 'aaaa';
final DocumentSnapshot snapshot = await FirebaseFirestore.instance.collection('users').doc(docId).get();
snapshot.exists
? {
//TODO: your code here
debugPrint("no data found")
}
: {
//TODO: your code here
debugPrint("number is: ${snapshot['number']}"),
debugPrint("name is: ${snapshot['name']}"),
};
}

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

Read all documents from collection from firestore in Flutter

I try to read all documents from collection as a model List from firestore like the java code.
Java code is
FirebaseFirestore.getInstance().collection("Product").addSnapshotListener((value, error) -> {
if (!value.isEmpty()){
List<Product> productList = value.toObjects(Product.class);
}
});
I try in flutter
QuerySnapshot data;
List<DocumentSnapshot> snapshot = new List<DocumentSnapshot>();
List<Product> productList = [];
data = await FirebaseFirestore.instance
.collection('Product')
.get();
snapshot.addAll(data.docs);
productList = snap.map((e) => Product.fromFirestore(e)).toList();
but always the list is empty, but the snapshot length is always same as my database.
database
Model class
void getProducts () async {
List<Product> productList = [];
var productsFromFirebase = await FirebaseFirestore.instance.collection("Product").get();
if (productsFromFirebase.docs.isNotEmpty) {
for (var doc in productsFromFirebase.docs) {
productList.add(Product.fromFirestore(doc)); //without '.data()' because you have it in your model.
}
}
print(productList.length); //prints the length of your products list.
}