Jess
Jess

Reputation: 28

Fetch information from realtime database in flutter

I would like to know how I can get the value of the post which is 4 from the realtime database in flutter. I tried this and it is not working.

  Future<Query> querystats() async {
      var user = await firebaseauth.currentUser();
      _userid = user.uid;
      return FirebaseDatabase.instance.reference().child("stats").child("another");
    }

 querystats().then((query) {
      query.once().then((snapshot) async {
        var snapshot = await query.once();
        var result = snapshot.value.values as Iterable;
        for (var item in result) {
          print(item['posts']);
        }

][2]][2] [enter image description here]1

Upvotes: 0

Views: 88

Answers (1)

Frank van Puffelen
Frank van Puffelen

Reputation: 598817

If you just want to read the value of a single property, you don't need the loop and Iterable.

It can be something like:

var user = await firebaseauth.currentUser();
_userid = user.uid;
var query = FirebaseDatabase.instance.reference().child("stats/another/posts");
var snapshot = await query.once()
var result = snapshot.value;
print(result);

The changes I made:

  • You can pass an entire path into child, which saves some characters.
  • Use await on the call to once(), so that you don't need a then block.
  • Remove the loop, since the snapshot now contains the exact value you're looking for.

I didn't run the code, but this should be pretty close.

Upvotes: 2

Related Questions