2021年3月30日星期二

Firestore, Flutter, Async: Method not waiting for async method to finish

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);    }  }  
https://stackoverflow.com/questions/66880882/firestore-flutter-async-method-not-waiting-for-async-method-to-finish March 31, 2021 at 10:35AM

没有评论:

发表评论