How to show real time data from from realtime database?

Viewed 69

I'm making this realy simple project where when you click a button, it increments a value in the realtime databse. This works, but I want a Text widget to update everytime the value changes. I've really new to this so please excuse my lack of knowledge. I have noticed that there's no snapshots methods available that would let me do something like this, so how I update a label to be the data in the realtime storage eveyime it changes? Here's the code which I use to increment the values-

Future<void> addData(int id) async {
    DatabaseReference pointsRef = FirebaseDatabase.instance.ref("$id");
    DataSnapshot snapshot = await pointsRef.get();
    pointsRef.set((snapshot.value as int) + 1);
  }

1 Answers

Use StreanBuilder like so:

 StreamBuilder(
   stream: FirebaseDatabase.instance.ref("id").onValue,
   builder: (context, snapshot) {
     if (!snapshot.hasData) {
       return Center(
          child: CircularProgressIndicator(),
        );
      }
      return Text(snapshot.data.toString());
      },
    )
Related