【发布时间】:2021-06-27 01:21:46
【问题描述】:
我正在构建一个使用 API 获取加密货币价格的 Flutter 应用。我将我的 API 密钥存储在 Firestore 数据库中,我目前能够从 Firestore 检索 API 密钥以在我的应用程序中使用。我遇到的问题是,当buildURL() 运行时,它不会等待String apiKey = await getApiKey(); 在继续之前完全完成,导致apiKey 从buildURL() 打印为Null。
我在getApiKey() 和buildURL() 中添加了打印语句来跟踪apiKey 的值,似乎buildURL() 的打印语句在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);
}
}
【问题讨论】:
标签: firebase flutter asynchronous google-cloud-firestore async-await