Reputation: 262
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 for String apiKey = await getApiKey();
to completely finish before continuing on, resulting in apiKey
to be printed as Null from buildURL()
.
I added print statements inside of getApiKey()
and buildURL()
to track the value of apiKey
and it seems that the print statements from buildURL()
are ran before the print statements from getApiKey()
.
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);
}
}
Upvotes: 1
Views: 750
Reputation: 1812
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"];
});
}
Upvotes: 1
Reputation: 914
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"]
}
Upvotes: 1
Reputation: 1762
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;
}
Upvotes: 1