【问题标题】:Firestore, Flutter, Async: Method not waiting for async method to finishFirestore,Flutter,Async:方法不等待异步方法完成
【发布时间】:2021-06-27 01:21:46
【问题描述】:

我正在构建一个使用 API 获取加密货币价格的 Flutter 应用。我将我的 API 密钥存储在 Firestore 数据库中,我目前能够从 Firestore 检索 API 密钥以在我的应用程序中使用。我遇到的问题是,当buildURL() 运行时,它不会等待String apiKey = await getApiKey(); 在继续之前完全完成,导致apiKeybuildURL() 打印为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


    【解决方案1】:

    你没有从你的 getApiKey 函数中返回

    getApiKey() {
        return FirebaseFirestore.instance
            .collection("myCollection")
            .doc("myDocument")
            .get()
            .then((value) {
          print("Api Key from getApiKey():");
          print(value.data()["Key"]);
          return value.data()["Key"];
        });
      }
    

    【讨论】:

      【解决方案2】:

      你想试试

        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;
        }
      

      【讨论】:

        【解决方案3】:

        为了等待一个函数,它需要是一个异步函数。 需要将asyncawait添加到getApiKey()来等待函数。

         Future<String> getApiKey() async {
            var result = await FirebaseFirestore.instance
                .collection("myCollection")
                .doc("myDocument")
                .get();
            return result.data()["Key"]
          }
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2019-10-19
          • 2014-08-09
          • 2013-02-15
          • 1970-01-01
          • 1970-01-01
          • 2013-08-19
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多