Flutter (Dart) remove firebase database Listener

Refresh

April 2019

Views

509 time

1

I add an firebase database Listener to my flutter project as below:

databaseReference = database.reference().child("community_board");
databaseReference.onChildAdded.listen(_onEntryAdded);
databaseReference.onChildChanged.listen(_onEntryChanged);

For Kotlin and swift of firebase, I have to remove the listener in onPause()/onDestroy(). May I know how to remove the firebase database listener in flutter?

GPH

1 answers

3
var sub1 = databaseReference.onChildAdded.listen(_onEntryAdded);
var sub2 = databaseReference.onChildChanged.listen(_onEntryChanged);

sub1.cancel();
sub2.cancel();

If you have this code in a widget you can use

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