SOS video
SOS video

Reputation: 476

Getting firebase data in a stream

I built an application, which gets data from the firebase (realtime db). I did it whith this code, but I want, that I always get the new data. In the internet I found something like in a stream, but I didn't find a manual for that.

Does somebody know how this works?

This is my code:

  void readData() {
    FirebaseDatabase.instance.reference().child('CHECK').once().then(
      (DataSnapshot dataSnapShot) {
        print(dataSnapShot.value);
      },
    );
  }

Upvotes: 0

Views: 4761

Answers (2)

Frank van Puffelen
Frank van Puffelen

Reputation: 598847

I want to get the data for example every 0.5 seconds

That's not really how Firebase works. But if you want to get the data from the database once right away, and then whenever it is updated, you can use onValue for that.

That'd look something like:

FirebaseDatabase.instance.reference().child('CHECK').onValue.listen((event) {
  print(event.snapshot.value);
});

Give it a try: just set up the listener with this code, run the app, and then make a change to the database in the Firebase console. You'll see the data be printed once as soon as you run the app, and then again whenever you make a change.

Upvotes: 4

Bilaal Abdel Hassan
Bilaal Abdel Hassan

Reputation: 1379

From what I've read in your comments, you want the function to be executed repeatedly every 0.5 seconds.

A stream is not appropriate for that. However, you can use Timer

@override
void initState() {
  super.initState();
  timer = Timer.periodic(Duration(seconds: 15), (Timer t) => readData());
}

@override
void dispose() {
  timer?.cancel();
  super.dispose();
}

Your build() function will be called more than once once Timer.periodic is created.

Upvotes: 1

Related Questions