0

I'm trying to get data from firebase and it worked with once().then function, but the problem is when I save the data a variable, its value will change only inside the function ( when the execution of the function is finished then the variable will not have the returned value from firebase ) code example :

static var temp = [];
  void tempp() {
    var db = FirebaseDatabase.instance.reference();
    db.once().then((DataSnapshot snapshot) {
      temp.add(1);
      print(temp[0]);
    });
    print(temp[0]);
  }

So, the first print statement will print the new value in temp list which is at index zero but for the second print ( outside the once().then function ) will cause value range error Invalid value: Valid value range is empty: 0 that means the value that was saved in the function it is not there anymore How can I save the value after function is executed ? I tried to use global variables it didn't work, your help is much appreciated. thank you.

Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807
  • Checkout [this answer](https://stackoverflow.com/questions/68450476/fetch-values-from-firestore-and-store-the-output-as-global-using-async/68450569#68450569). It's Javascript but the concept of asynchronous should be same/ – Dharmaraj Jul 23 '21 at 02:53
  • 1
    Also see https://stackoverflow.com/questions/40688268/why-does-firebase-lose-reference-outside-the-once-function/40688890#40688890 – Frank van Puffelen Jul 23 '21 at 06:03
  • Thank you very much it worked with async and await. – george ghawali Jul 23 '21 at 16:09

0 Answers0