Flutter and Firebase: Get DocumentSnapShot Based On Current User ID - firebase

Here's my code to get current user documentsnapshot from database.
Future getCurrentUSerData() async {
final DocumentSnapshot doc = await userRef.document(currentUserId).get();
currentUser = MyUser.fromDocument(doc);
}
I got the currentUserId. there is no problem with that.
2.userRef is the reference to the users in firebase (final userRef = Firestore.instance.collection('users');)
but when I checked currentUser value, the value is returned as null.
Problem - How to get the current user data based on current user id?

Please change
final DocumentSnapshot doc = await userRef.document(currentUserId).get();
to
final DocumentSnapshot doc = await userRef.doc(currentUserId).get();

Related

How to also update user's name and image in comments sub-collection in Flutter via Firestore

In my app, users can comment on every post and the comments are stored in the post's sub-collection: 'comments'. Each comments' document contains the poster's username, profile image, user Id, comment Id and some other fields.
So I'm trying to also update each comments' document that contains a current user's userId when that user updates their profile.
I have only been able to achieve the code below;
//Uploading the new image to storage
final firebaseUser = FirebaseAuth.instance.currentUser!;
final String uids = firebaseUser.uid;
final Reference storageReference =
FirebaseStorage.instance.ref().child("userImages- $uids");
UploadTask uploadTask = storageReference.putFile(imageTemp);
String downloadUrl = await (await uploadTask).ref.getDownloadURL();
//Updating users' document with the new image
final CollectionReference users =
FirebaseFirestore.instance.collection("users");
final String uid = firebaseUser.uid;
String url = downloadUrl;
await users.doc(uid).update({'url': url});
//Trying to also update users' comments document with the image
final CollectionReference posts =
FirebaseFirestore.instance.collection("posts");
await posts
.doc()
.collection('comments')
.doc()
.update({'profilePic': url});
How can I possibly achieve this? Any help will be appreciated.
You could do something like this
await users.doc(uid).update({'url': url}).then((value2) {
FirebaseFirestore.instance
.collection('posts')
.doc('postDOCID')
.collection('comments')
.where('uid', isEqualTo: curUserUID)
.get()
.then((value) => value.docs.forEach((element) {
element.data().update('userImageURL', (value) => "url");
}));
});
Basically, what you will need to do is loop through or search with where through post documents where userId = currentUpdatedUID.
Once you find it, loop the list and update each one of them.
Let me know if any issue comes up.
Cheers!!

How to access user information from an array list that stores user uids in Flutter using Firestore

Okay, so in my cloud firestore, I have a system set up where a user can create or join a group. This is done by a unique groupId being created for that user, which is used as the document path for a collection called groups where information for that group is stored, most importantly being the member list. So far I store users by their uid. However, I've gotten to the point where soon I want to display member's information like member names, photos, etc. The problem is that I do not know how to properly access information inside a firestore array, in this case being the uids from which I can use those uids as a path to get user display names, and other stuff.
Here is a photo showing the Groups collection, with teh groupId path and the member array:
Here is my attempt to access the member array:
final firestore = FirebaseFirestore.instance;
FirebaseAuth auth = FirebaseAuth.instance;
Future<List<String>> getGroupMembers() async {
final CollectionReference users = firestore.collection('UserNames');
final String uid = auth.currentUser.uid;
final result = await users.doc(uid).get();
final groupId = result.data()['groupId'];
final CollectionReference groups = firestore.collection('Groups');
final groupMembersResult = await groups.doc(groupId).get();
return groupMembersResult.data()['members'];
}
What I have done here is getting the unique user uid, and from that access the user's groupId value. I use that groupId value as a pathway in the Groups Collection to acess that specific group's information. How can I specifically access the contents inside of the member array?
You can access an array list as you do it in an object that contains an array. In your case you would have something like :
Future<List<String>> getGroupMembers() async {
final String uid = auth.currentUser.uid;
final currentUser = [];
final groups = [];
// Get User document
await firestore
.collection('UserNames')
.document(uid)
.get()
.then((DocumentSnapshot snapshot) {
currentUser.add(snapshot.data);
});
// Get groupeId from currentUser Data
final groupId = currentUser[0]['groupId'];
// Get groupe Document
await firestore
.collection('Groups')
.document(groupId)
.get()
.then((DocumentSnapshot snapshot) {
groups.add(snapshot.data);
});
return groups[0]['members'];
}

Update Firestore document where user_id is same as currentUser uid

I have the function that I am using to create or update customer.
I am able to successfully write to db. I created a field called user_id where I save the currentUser uid into so I can read only logged in user documents.
However, I am unable to update the documents because I know I'm probably not referencing the document the right way.
I get the following error:
flutter: Error: PlatformException(Error 5, FIRFirestoreErrorDomain, No
document to update:
What am I doing wrong?
Here's my function below:
Future createOrUpdateCustomer(Customer customer, bool isUpdating) async {
FirebaseUser user = await FirebaseAuth.instance.currentUser();
String userId = user.uid;
print('Current logged in user uid is: $userId');
CollectionReference customerRef =
await Firestore.instance.collection('customers');
if (isUpdating) {
customer.updatedAt = Timestamp.now();
customer.userId = userId;
await customerRef.document().updateData(customer.toMap());
print('updated customer with id: ${customer.id}');
print('updated customer with logged in uid: ${customer.userId}');
} else {
customer.createdAt = Timestamp.now();
DocumentReference documentReference = customerRef.document();
customer.id = documentReference.documentID;
customer.userId = userId;
print('created customer successfully with id: ${customer.id}');
await documentReference.setData(customer.toMap(), merge: true);
addCustomer(customer);
}
notifyListeners();
}
You are trying to update a nonexistent document. In this line,
await customerRef.document().updateData(customer.toMap())
You are creating a document reference with a randomly-generated id. You should explicitly set the id of the document you're updating.
I think you can update the document with conditions but the reference must be the doc id, that you see in 2nd section of firestore interface.

how to query in firebase select condition where date is datenow

I'm trying to query in my flutter application to show the user's input data that sort by date now. I have tried this
Stream<QuerySnapshot> getUserWorshipSnapshots(BuildContext context) async*{
//final Long server_timestamp = new DateTime.now().isUtc;
var currentTime = new DateTime.now();
final FirebaseUser user = await _auth.currentUser();
final uid = user.uid;
yield* Firestore.instance.collection('user').document(uid).collection('worship').orderBy('dateTime')
.startAt(currentTime).snapshots();}
, and my firebase structure is like this . is there any idea? thank you
You have a users collection and not a user collection, therefore add the missing s:
yield* Firestore.instance.collection('users').document(uid).collection('worship').orderBy('dateTime')

Flutter place filter based on variable in firestore request

I am working on an app which requests based on the registered Userid certain elements from my firestore.
Now i'm trying to build the Notifier related to this but somehow it breaks when putting the filter in the firestore request
import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:tutora/states/question_notifier.dart';
import 'package:tutora/models/answers.dart';
import 'package:firebase_auth/firebase_auth.dart';
Future<String> id() async {
FirebaseUser user = await FirebaseAuth.instance.currentUser();
String userID = user.uid.toString();
return userID;
}
getAnswers(AnswerNotifier answerNotifier) async {
QuerySnapshot snapshot = await Firestore.instance
.collection('Questions')
.where(
'UserID',
isEqualTo: await id(),
)
.getDocuments();
List<Answer> _answerList = [];
snapshot.documents.forEach((document) {
Answer answer = Answer.fromMap(document.data);
_answerList.add(answer);
});
answerNotifier.answerList = _answerList;
}
What in my head this should do is that it gets the current user ID and then based on that ones only collects the Questions which match on the column UserID.
This works perfectly fine if i manually enter the UserID in my code however the moment where it requests the current user ID from id() it does not find any matching questions. So my question list in the app is empty as well as ofc my _answerList here.
The user is logged in at this point in the app where this Answernotifier is called.
Thankful for any help this is really bugging me now quit some time.
Try the following:
getAnswers(AnswerNotifier answerNotifier) async {
String userId = await id();
QuerySnapshot snapshot = await Firestore.instance
.collection('Questions')
.where('UserID',isEqualTo: userId).getDocuments();
get the userId first and then use the result inside the where() query.

Resources