'In Flutter, using await stores data correctly, but not collection name and not using await does not store data correctly, but correct collection name
My current code uses:
var currentUID = await database.getCurrentUserID();
Running this function with await on this line of code stores data in Firestore with correct user ID but time is always set to 0:

Future<void> addUserTime() async {
var currentUID = await database.getCurrentUserID();
return await database.workoutCollection
.doc(currentUID.toString())
.set({
'Workout Time': format(duration),
})
.then((value) => print('Time added'))
.catchError((error) => print('Failed to add time to database'));
}
Without using await like the previous line of code like this:
var currentUID = database.getCurrentUserID();
Firestore shows this: This is the firebase output. Wrong UserID from Firebase Authentication, but time is always set to what the user logged:

Future<void> addUserTime() async {
var currentUID = database.getCurrentUserID();
return await database.workoutCollection
.doc(currentUID.toString())
.set({
'Workout Time': format(duration),
})
.then((value) => print('Time added'))
.catchError((error) => print('Failed to add time to database'));
}
This is my database class where I call the getCurrentUserID() function:

How can I get both the correct UID and correct time the user logged?
Solution 1:[1]
FirebaseAuth stores the current user once it's authenticated in FirebaseAuth.instance.currentUser, if we look into this property we will find that the type is User?, not Future<User?>, hence you don't need to await to get the currentUser, simply:
return FirebaseAuth.instance.currentUser?.uid;
Additionally, currentUser?.uid returns a String, so no need to call .toString().
Assuming that the duration is not 0, with these modifications the code should work, for further reference here's a DartPad example that updates a user record based on currentUser.uid.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Mais Alheraki |
