Override dispose method in a ChangeNotifier

Issue

I have the following model

class SelectorModel with ChangeNotifier {
    .... // stuff relating to the model
}

and inside my model I’m getting a stream of Firestore documents using the following:

_subscription = Firestore.instance   // _subscription is defined as an iVar above
      .collection('myCollection')
      .snapshots()
  .listen((querySnapshot)  {
    _jobs = querySnapshot.documents;
    callingMethod('');  // the method being called is inside of my model
  });

I need a way to dispose of the _subsciption so that when a change occurs in my Firestore database, it will not attempt to call callingMethod() when my model has already been disposed.

What I’m looking for is a method almost like the following for a ChangeNotifier:

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

I looked through the provider docs but could not find anything.

Thanks for any help!

Solution

You can do it like that if i understand you

_subscription = Firestore.instance   // _subscription is defined as an iVar above
      .collection('myCollection')
      .snapshots()
  .listen((querySnapshot)  {
    _jobs = querySnapshot.documents;
    callingMethod('');  // the method being called is inside of my model
   _subscription.cancel();
  });

Answered By – Cenk YAGMUR

Answer Checked By – Mildred Charles (FlutterFixes Admin)

Leave a Reply

Your email address will not be published. Required fields are marked *