I'd like to know how can i store in a variable in the state of the application the return value of a future in a flutter app ?
For example :
List usernames = await AuthMethods().getCurrentUserInvitations()
Where the method getCurrentUserInvitations returns a list.
I only get the instance not the actual return of the future.
Future<List> getCurrentUserInvitations() async {
List usernames = [];
try {
var snap = await _firestore
.collection("users")
.doc(_auth.currentUser!.uid)
.get();
print(snap.data()!["invitedBy"]);
snap.data()!["invitedBy"].forEach((invitedById) async {
try {
var snap =
await _firestore.collection("users").doc(invitedById).get();
print(snap.data()!["username"]);
usernames.add(snap.data()!["username"]);
} catch (e) {
print(e.toString());
}
});
} catch (e) {
print(e.toString());
}
return usernames;
}
added the code from the method
CodePudding user response:
If you are trying to just store the future into a variable, there is a pretty straight forward way to do that. In your code, change it to
Future<List> usernames = AuthMethods().getCurrentUserInvitations()
And then, when you want to access the data returned in the Future, you will have to wait for that Future to get completed. For example, if you want to calculate the length of the List, do
Future<List> usernames = AuthMethods().getCurrentUserInvitations()
.
.
.
/* ... Code that doesn't need value of usernames ... */
.
.
.
/* Then when you want the actual values, */
List actualUsernames = await usernames;
print(actualUsernames.length);