Firestore, Flutter, Async: Method not waiting for async method to finish
Solution 1
You are not returning from you getApiKey function
getApiKey() {
return FirebaseFirestore.instance
.collection("myCollection")
.doc("myDocument")
.get()
.then((value) {
print("Api Key from getApiKey():");
print(value.data()["Key"]);
return value.data()["Key"];
});
}
Solution 2
In order to await a function it needs to be an async function.
Adding async
and await
to getApiKey()
is needed to await the function.
Future<String> getApiKey() async {
var result = await FirebaseFirestore.instance
.collection("myCollection")
.doc("myDocument")
.get();
return result.data()["Key"]
}
Solution 3
Would you mind to try
Future<String> getApiKey() async {
String result=await FirebaseFirestore.instance
.collection("myCollection")
.doc("myDocument")
.get()
.then((value) {
print("Api Key from getApiKey():");
print(value.data()["Key"]);
return value.data()["Key"];
});
return result;
}
CuriousCoder
Updated on December 28, 2022Comments
-
CuriousCoder 11 months
I'm building a Flutter app that uses an API to fetch cryptocurrency prices. I stored my API Key in a Firestore database and I am currently able to retrieve the API Key from Firestore to use in my app. The problem I'm having is that when
buildURL()
is ran it doesn't wait forString apiKey = await getApiKey();
to completely finish before continuing on, resulting inapiKey
to be printed as Null frombuildURL()
.I added print statements inside of
getApiKey()
andbuildURL()
to track the value ofapiKey
and it seems that the print statements frombuildURL()
are ran before the print statements fromgetApiKey()
.I/flutter ( 2810): Api Key from buildURL(): I/flutter ( 2810): null I/flutter ( 2810): Api Key from getApiKey(): I/flutter ( 2810): 123456789
import 'package:cloud_firestore/cloud_firestore.dart'; class URLBuilder { URLBuilder(this.cryptoCurrency, this.currency, this.periodValue); String cryptoCurrency; String currency; String periodValue; String _pricesAndTimesURL; String get pricesAndTimesURL => _pricesAndTimesURL; getApiKey() { FirebaseFirestore.instance .collection("myCollection") .doc("myDocument") .get() .then((value) { print("Api Key from getApiKey():"); print(value.data()["Key"]); return value.data()["Key"]; }); } buildURL() async { String apiKey = await getApiKey(); _pricesAndTimesURL = 'XXXXX/XXXXX/$cryptoCurrency$currency/ohlc?periods=$periodValue&apikey=$apiKey'; print("Api Key from buildURL():"); print(apiKey); } }