How to create one time listener for ChangeNotifier in dart

1.2k Views Asked by At

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.

2

There are 2 best solutions below

1
On BEST ANSWER
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);
  }
}
0
On
import 'package:flutter/foundation.dart';

void main() {
  var valueNotifier = ValueNotifier<int>(0);  
  VoidCallback? listener;
  listener = () {
    debugPrint("Run callback");
    valueNotifier.removeListener(listener!);    
  };  
  valueNotifier.addListener(listener);
  
  valueNotifier.value = 1;
  valueNotifier.value = 2;
  valueNotifier.value = 3;
}

Example above with ValueNotifier since ChangeNotifier does not allow calling notifyListeners from outside

To call notifyListeners, you must extend ChangeNotifier:

import 'package:flutter/foundation.dart';

class OpenNotifier extends ChangeNotifier {
  void notify() {
    notifyListeners();
  }
}

void main() {
  var notifier = OpenNotifier();  
  VoidCallback? listener;
  listener = () {
    debugPrint("Run callback");
    notifier.removeListener(listener!);    
  };  
  notifier.addListener(listener);
  
  notifier.notify();
  notifier.notify();
  notifier.notify();
}