how to display documents firestoredatabase in home screen flutter - firebase

I want to display the documents in Firestore database in home screen by using snapshot
I need something like this
Text('documents["name"]')

Use this code:
List<String> _groupsId = [];
await fireStore
.collection('groups')
.get()
.then((QuerySnapshot querySnapshot) {
for (var doc in querySnapshot.docs) {
_groupsId.add(doc.id);
}
});
You will get all list key of documents

Related

Update a field in the last document in Firestore collection Flutter

I am trying to update a field in the last document in the Firestore collection. My updating method is below:
updateHours() {
return usersRef.doc(firebaseAuth.currentUser!.uid).collection('posts')
.orderBy('datePublished', descending: true)
.limit(1).get().then((querySnapshot) {
return querySnapshot.docs.map((e) {
usersRef
.doc(firebaseAuth.currentUser!.uid).collection('posts')
.doc(e.reference.id)
.update({"totalTime": FieldValue.increment(1)});
});
});
}
This does not work. If I use .forEach(), then all documents get updated. So, how to update only the last document field?
To be able to update the totalTime field inside the last document, please use the following lines of code:
void updateHours() async{
CollectionReference postsRef = usersRef
.doc(firebaseAuth.currentUser!.uid)
.collection('posts');
QuerySnapshot query = await postsRef.orderBy('datePublished', descending: true)
.limit(1)
.getDocuments();
query.documents.forEach((doc) {
doc.reference.updateData({"totalTime": FieldValue.increment(1)});
});
}
Don't forget that Firebase APIs are asynchronous, and you need to wait for the data until it becomes available.

Firebase query doesn't get documents with a specific field

I'm running a query to get all documents from firebase containing a field of location contains, say 'Nairobi'. The structure of my database is /posts/[userId]/userPosts/[postId].
Now, when I specify the userId in my code, I get the documents.
QuerySnapshot snapshot = await FirebaseFirestore.instance.collection('posts')
.doc("1092987983578079255")
.collection('userPosts')
.where('location', isGreaterThanOrEqualTo: '${placemark.locality}')
.get();
setState(() {
posts = snapshot.docs.map((doc) => Post.fromDocument(doc)).toList();
isLoading = false;
});
However, when I try to get all the documents within the entire posts collection, I get null results.
QuerySnapshot snapshot = await FirebaseFirestore.instance.collection('posts')
.where('location', isGreaterThanOrEqualTo: '${placemark.locality}')
.get();
setState(() {
posts = snapshot.docs.map((doc) => Post.fromDocument(doc)).toList();
});
I have tried using the code
QuerySnapshot snapshot = await FirebaseFirestore.instance
.collectionGroup("userPosts")
.where('location', isGreaterThanOrEqualTo: '${placemark.locality}')
.get();
setState(() {
posts = snapshot.docs.map((doc) => Post.fromDocument(doc)).toList();
isLoading = false;
});
but I get the error Operation was rejected because the system is not in a state required for the operation's execution. If performing a query, ensure it has been indexed via the Firebase console.
given that, it is only querying through one criterion, I don't believe that a composite index is necessary but I, still, have created one.
adb logcat doesn't give me the link to create an index even if I wrap the code in try to catch the error e.
What am I missing?

Cannot display any data from firestore flutter

i am developing a flutter mobile apps and i have encountered few error. which is when im running my apps, the data is not displayed. I try to retrieve the uid and specific field to be display. This is the code for the retrieve part
and this is my database where i want to retrieve the type of the user database.
This is the output from my apps output
Change your query to this.
firestore
.collection("User")
.where("uid", isEqualTo: result.id)
.where("type", isEqualTo: "teacher")
.get();
void getTeacherData(){
firestore
.collection("User")
.where("type", isEqualTo: "teacher")
.get().then((querySnapshot){
//Check here if not null
querySnapshot.docs.forEach((element){
print(element["name"]);
});
});
}
this will give you all the user who are teachers
According to this documentation, your query should be as follows:
FirebaseFirestore firestore = FirebaseFirestore.instance;
Future getTeacherData() async {
firestore
.collection('User')
.where('type', isEqualTo: 'teacher')
.get()
.then((QuerySnapshot querySnapshot) {
querySnapshot.docs.forEach((result) {
print(result['uid']);
});
});
}
Please tell us if this worked for you.

How can I filter a map / Firestore Flutter

I need to search for data from a map in the "users" collection of a single document. But I only found ways to search all documents.
See below.
Code 1:
FirebaseFirestore.instance
.collection('users')
.get()
.then((QuerySnapshot querySnapshot) {
querySnapshot.docs.forEach((doc) {
Map<String, dynamic> res = doc["favorite"];
});
});
Code 2:
final String _collection = 'users';
final FirebaseFirestore _fireStore = FirebaseFirestore.instance;
getData() async {
return await _fireStore.collection(_collection).get();
}
getData().then((val) {
if (val.docs.length > 0) {
print(val.docs[0].data()["favorite"]);
} else {
print("Not Found");
}
});
Hello you can search in fields:
// Create a reference to the cities collection
var citiesRef = db.collection("cities");
// Create a query against the collection.
var query = citiesRef.where("state", "==", "CA");
See the Firestore queries reference here:
https://firebase.google.com/docs/firestore/query-data/queries

How do i create a timeline feed using firebase in flutter?

- posts
- userID
- userID
- randomID
- randomID
- followers
- personB userid
- personA userid
- following
- personA userid
- personB userid
This is how my firebase collection is organized.
how do i get create a timeline feed for current logged-in user where the timline posts should be of only from the logged-in user's following list?
Note:I dont want to use firebase functions.Is it possible with CRUD?
What ive tried so far.
getFollowing() async {
QuerySnapshot snapshot = await followersRef
.document(currentUser.id)
.collection('userFollowing')
.getDocuments();
setState(() {
followingList = snapshot.documents.map((doc) => doc.documentID).toList();
print(followingList);
});
}
getTimeline()async{
QuerySnapshot snapshot = await postsRef
.document(followingList)//getting an error here saying list<string> csn't be assigned to string.
.collection('userPosts')
.orderBy('timestamp', descending: true)
.getDocuments();
List<Post> posts =
snapshot.documents.map((doc) => Post.fromDocument(doc)).toList();
setState(() {
this.posts = posts;
});
}
The approach which I think is efficient is using A collection 'Posts' and document for each post, with an array inside the post document as a field.
This means when a user adds post you have to include the user's followers as a field(List<dynamic) inside the post.
- posts(Collection)
- post(Document)
- followers(List<dynamic>)
you can query post for users like
Firestore.instance.collection('posts').where('followers', arrayContains: currentUserId).snapshots();
//this brings all queries with the tagged users as followers aka the users that follow the poster will be able to query this post.
if you want to update the array you can use
FieldValue.arrayRemove or FieldValue.arrayUnion,
Edit: As a final warning I must mention that there is a limit to how much data there could be for one document, based on the scale of your app you have to decide whether to put a growing list (such as followers) inside one document or to create another collection for the growing list and give one document for each element since documents can't be limited (this approach could cost more).
List timelinePosts =[];
getFollowing() async {
QuerySnapshot snapshot = await followersRef
.document(currentUser.id)
.collection('userFollowing')
.getDocuments();
setState(() {
followingList = snapshot.documents.map((doc) => doc.documentID).toList();
print(followingList);
});
}
getTimeline()async{
List posts = [];
for( int i=0; i< followingList.length; i++)
{
QuerySnapshot snapshot = await postsRef
.collections('posts/${followingList[i]}/userPosts')
.orderBy('timestamp', descending: true)
.getDocuments();
posts+= snapshot.data.documents.map((doc) => {'id':doc.documentID,...doc.data}).toList();
}
setState(() {
timelinePosts = timeLinePosts + posts;
});
}
then u can use Listview.builder() on timelinePosts,
However this is not the most efficient method, since you are fetching all the posts at once. You can also implement fetch post as you scroll through the list, using Listview controller attribute

Resources