How to return an int from Firebase Realtime Database in Flutter

413

once() is asynchronous, the then() method will register callbacks to be called when this future completes. Therefore in your code 0 will always be returned since it is getting executed before the future is finishing.

To solve that, you can use async/await:

Future<int> GetInitial(String roomID) async {
    final dbRef = FirebaseDatabase.instance.reference().child(roomID).child("initial");
    final snapshot = await db.child(roomID).child('initial').once();
    print('Data : ${snapshot.value}');
    return int.parse(snapshot.value);
  }
Share:
413
Peter Haddad
Author by

Peter Haddad

If my answer helped you, you can support me by buying me a coffee. Want to be part of a fun community? Join Discord! Check out MVVM architecture in Flutter using Provider &amp; Retrofit Covid Tracker 11th user to earn the gold flutter badge(14/10/20) 9th user to earn the gold firebase badge (10/08/18) 20th user to earn the silver firebase badge (20/03/18) 47th user to earn the bronze firebase badge (11/01/18) Gold badges in firebase google-cloud-firestorefirebase-realtime-database android java flutter dart Silver badges in javascript firebase-authentication Helpful Articles: Using Firebase Storage in Flutter Using Cloud Firestore in Flutter Using Firebase Authentication in Flutter Using Firebase Queries in Flutter Get Started With Firebase In Flutter Using Null Safety in Dart Using Shared Preferences in Flutter Using SQLite in Flutter Using Floor Plugin in Flutter Sending Emails In Flutter Using Google Sign-in With Firebase In Flutter Using Provider In Flutter Using GetIt In Flutter Using Firebase With Bloc Pattern in Flutter

Updated on December 30, 2022

Comments

  • Peter Haddad
    Peter Haddad over 1 year
    int GetInitial(String roomID) {
        final dbRef =
            FirebaseDatabase.instance.reference().child(roomID).child("initial");
        db.child(roomID).child('initial').once().then((DataSnapshot snapshot) {
          print('Data : ${snapshot.value}');
          return int.parse(snapshot.value);
        });
        return 0;
      }
    

    I'm trying to return the value of a child in my Firebase Realtime Database JSON tree, but it keeps giving me zero. I cannot access the value directly using once() as the return value is wrong. The output that I get from printing the value to the console is correct however, however it does not return int.parse(snapshot.value).

  • Admin
    Admin almost 3 years
    I changed it to return snapshot.value() since int.parse() does not work on non-string values, and it returns a future<int>, which I am unable to convert to an int
  • Peter Haddad
    Peter Haddad almost 3 years
    you need to use futurebuilder widget to get the int value api.flutter.dev/flutter/widgets/FutureBuilder-class.html