notifier.dart 1.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  1. import 'package:flutter/material.dart';
  2. abstract class Comparable<T> {
  3. bool compare(T? previous, T? current);
  4. }
  5. class ObjectComparable<T> extends Comparable<T> {
  6. @override
  7. bool compare(T? previous, T? current) {
  8. return previous == current;
  9. }
  10. }
  11. class PublishNotifier<T> extends ChangeNotifier {
  12. T? _value;
  13. Comparable<T>? comparable = ObjectComparable();
  14. PublishNotifier({this.comparable});
  15. set value(T newValue) {
  16. if (comparable != null) {
  17. if (comparable!.compare(_value, newValue)) {
  18. _value = newValue;
  19. notifyListeners();
  20. }
  21. } else {
  22. _value = newValue;
  23. notifyListeners();
  24. }
  25. }
  26. T? get currentValue => _value;
  27. void addPublishListener(void Function(T) callback,
  28. {bool Function()? listenWhen}) {
  29. super.addListener(
  30. () {
  31. if (_value == null) {
  32. return;
  33. } else {}
  34. if (listenWhen != null && listenWhen() == false) {
  35. return;
  36. }
  37. callback(_value as T);
  38. },
  39. );
  40. }
  41. }
  42. class Notifier extends ChangeNotifier {
  43. void notify() {
  44. notifyListeners();
  45. }
  46. }