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

388

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;
  }
Share:
388
CuriousCoder
Author by

CuriousCoder

Updated on December 28, 2022

Comments

  • CuriousCoder
    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 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);
      }
    }