How to fetch data from Firestore and display them in Flutter? - flutter

I'm a beginner in Flutter and firestore. I have a collection in firestore with following order:
event->'a user specific id'->post->'a post id->'post details'. you can see hereFirestore1 and hereFirestore2
When I try to fetch the 'postdetails', only thing I get is 'Instance of 'DocumentSnapshot',see hereResponse
What i tried:
getEvents() async {
setState(() {
_isLoading = true;
});
DocumentSnapshot snapshot = await eventref
.doc(uid)
.collection('post')
//.orderBy('Date', descending: true)
.doc()
.get();
print('Snapshot : ${snapshot}');
return snapshot;
// setState(() {
// _isLoading = false;
// print(event);
// });
}
I have also made a model for events. See hereEvent Model
I want to fetch data and display them as card.
Any help?
Thanks in Advance

print('Snapshot : ${snapshot.data()["Date"]}');
Using data() you can access the fields value.

snapshot.get("field_name")
You need to ask flutter to retrieve the fields inside the document snapshot.
Will need a more detailed order of your firestore collection and document to provide the exact code. You may follow the sample below:
On firestore:
-Collection: "users"
---Document: "userId"
-------Field: "username"
-------Field: "birthdate"
Code:
DocumentSnapshot doc =await _firestore.collection("users").doc(userId).get();
print(doc.get('username'));
print(doc.get('birthdate'));

Related

Flutter - Snapshot from Sub-collection

I was reading several answers here but I could not get better understanding to solve my issue which is the following...
I don't know how to get the "docId" in the code below...
I want to query a sub-collection "People" as snapshot for the stream method which I will listen using Bloc...
I am not able to understand how to get the docId. Anyone could help me with this?
Thanks
Stream<People> statusMember({required String email}) {
var user = auth.FirebaseAuth.instance.currentUser;
final snap = _firestore
.collection('users')
.doc(user!.email)
.collection('people') //sub-collection
.doc(docId) // docId as reference? How to get it?
.snapshots()
.map((snapshot) => People.fromSnapshot(snapshot)); // model
print(snap);
return snap;
}
By digging more into the Firebase documentation, it is not possible to read docs in a sub-collection the way I wanted. Therefore, I've changed my approach and the code looks like this:
Stream<People?> statusMember({required String email}) {
var user = auth.FirebaseAuth.instance.currentUser;
final snap = _firestore
.collection('users')
.doc(user!.email)
.collection('people')
.where('email', isEqualTo: email)
.snapshots()
.map(
(snappshot) {
for (var doc in snappshot.docs) {
return People.fromSnapshot(doc);
}
},
);
print(snap);
return snap;
}
it is working as expected.

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

Problem while reading document from firestrore in flutter

I am new to Firebase I want to read all data of document here is how i am trying to read
This is my function to get data.
Future<List<AgencyModel>> getAgencyData() async {
List<AgencyModel> agencyListModel = [];
try {
agencyListModel = await _db.collection('colelctionName')
.doc('myDoc')
.snapshots()
.map((doc)=> AgencyModel.fromJson(doc.data()!)).toList();
print('List : ${agencyListModel.length}');
return agencyListModel;
} catch (e) {
debugPrint('Exception : $e');
rethrow;
}
}
This is how i am calling the above function
getAgencyDetails() async {
List<AgencyModel> data = await fireStoreService.getAgencyData();
print('Data : ${data.first}');}
and this is my models class fromjson function
factory AgencyModel.fromJson(Map<String, dynamic> json) {
return AgencyModel(
agencyName: json['agencyName'],
agencyContact: json['agencyContact'],
agencyAddress: json['agencyAddress'],
cnic: json['cnic'],
agencyContactDetails: json['agencyContactDetails'],
certificatesUrl: json['certificatesUrl'],
locationUrl: json['locationUrl'],
earning: json['earning'],
processing: json['processing'],
onHold: json['onHold']);}
I am not getting any error or exception, Also these two print statements does not work not display anything not even the Strings List : and Data : i.e
print('List : ${agencyListModel.length}');
print('Data : ${data.first}');}
UPDATE:
According to the documentation:
https://firebase.google.com/docs/firestore/query-data/get-data#dart_1
It is necessary to distinguish whether you want to retrieve the data only once or listen to changes over the document in real time.
It seems to me like you want to accomplish 1. case that you only want to retrieve data once. In that case.
You should change:
agencyListModel = await _db.collection('collectionName')
.doc('myDoc')
.snapshots()
agencyListModel = await _db.collection('collectionName')
.doc('myDoc')
.get()

Flutter - Stream not returning data

I have a document collection called posts_favorites, which stores the reference to all the Posts that a user has bookmarked. The posts_favorites collection look as follows:
I have created a Stream to get all posts references that belong to a specific user, then I want to get the Post documents from the posts collection using the posts references.
I created a Stream to produce the data I need, but I am not getting any data returned from my Stream. Here is my code for the Stream:
Stream<List<PostsRecord>> getFavoritePostsStream() async* {
List<PostsRecord> myList = [];
await FirebaseFirestore.instance
.collection("posts_favorites")
.where("user", isEqualTo: currentUserReference)
.get()
.then((favoriteList) {
favoriteList.docs.forEach((element) async {
String documentPath = element['post'].toString();
var start = documentPath.indexOf("/");
var end = documentPath.indexOf(")");
var documentRef = documentPath.substring(start+1, end);
//DocumentReference docRef = FirebaseFirestore.instance.doc(documentPath);
DocumentReference docRef = FirebaseFirestore.instance.collection('posts').doc(documentRef);
await docRef.get().then((DocumentSnapshot documentSnapshot) async {
if (documentSnapshot.exists) {
print('Document exists on the database');
PostsRecord postsRecord = PostsRecord.getDocumentFromData(
documentSnapshot.data(), element['post']);
//return myList.add(postsRecord);
//print(postsRecord);
return postsRecord;
}
});
});
});
}
I know this function works because the commented code produces the Post Records that I expect to get from Firestore.
I am not sure how to get the Stream function to return data that I can use in the Stream.
Thank you

How to get data from nested collection in Flutter firestore?

I am using provider and Stream to fetch data from Firestore. so now i want to access the inner collection. but i am not able to fetch the data. How can i access myOrders collection.
this is the structure of firestore.
i tried this code to fetch but not worked for me.
//Store data into myOrders collection
Future myOrders(String image, String price) async {
final FirebaseUser user = await _auth.currentUser();
return await userData
.document(user.uid)
.collection('myOrders')
.document()
.setData({
'orderedImage': image,
'orderedPrice': price,
});
}
// get the data as snapshot
List<OrderedModel> myOrderSnapShot(QuerySnapshot snapshot) {
return snapshot.documents.map((doc) {
return OrderedModel(
orderedImage: doc.data['orderedImage'] ?? '',
orderedPrice: doc.data['orderedPrice']);
}).toList();
}
// get the snapshot as stream
Stream<List<OrderedModel>> get orderedStream {
return userData.document(uid).collection('myOrders').snapshots().map(myOrderSnapShot);
}```
did you try printing the values and debug the code?