flutterdartlistenerchangenotifier

How to create one time listener for ChangeNotifier in dart


I want to add a listener to a ChangeNotifier. And trigger this listener only once. For example:

final changeNotifier = ChangeNotifier();
changeNotifier.addListener(() {
  debugPrint("Run callback");
});
changeNotifier.notifyListeners();
changeNotifier.notifyListeners();
changeNotifier.notifyListeners();

This code will print 3 times "Run callback". I want to print "Run callback" only once. How to do that.


Solution

  • extension ChangeNotifierExtension on ChangeNotifier {
    
      void addOneTimeListener(VoidCallback listener) {
        addTimeListenerUntil(() {
          listener();
          return true;
        });
      }
    
      void addTimeListenerUntil(bool Function() listener) {
        VoidCallback? l;
        l = () {
          bool stop = listener();
          if (stop && l != null) {
            removeListener(l);
          }
        };
        addListener(l);
      }
    }