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();
}