customer_notifier.dart 1.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. class CustomNotifier<T> {
  2. List<void Function(T value)> callBacks = [];
  3. bool _lockList = false;
  4. void addListener(void Function(T value) func) {
  5. if (_lockList) {
  6. Future.delayed(const Duration(milliseconds: 1)).then((v) {
  7. addListener(func);
  8. });
  9. return;
  10. }
  11. _lockList = true;
  12. callBacks.add(func);
  13. _lockList = false;
  14. }
  15. bool get hasListeners => callBacks.isNotEmpty;
  16. void removeListener(void Function(T value) func) {
  17. if (_lockList) {
  18. Future.delayed(const Duration(milliseconds: 1)).then((v) {
  19. removeListener(func);
  20. });
  21. return;
  22. }
  23. _lockList = true;
  24. callBacks.remove(func);
  25. _lockList = false;
  26. }
  27. void notifyListeners(T value) {
  28. if (_lockList) {
  29. Future.delayed(const Duration(milliseconds: 1)).then((v) {
  30. notifyListeners(value);
  31. });
  32. return;
  33. }
  34. _lockList = true;
  35. for (var element in callBacks) {
  36. element(value);
  37. }
  38. _lockList = false;
  39. }
  40. void dispose() {
  41. if (_lockList) {
  42. Future.delayed(const Duration(milliseconds: 1)).then((v) {
  43. dispose();
  44. });
  45. return;
  46. }
  47. _lockList = true;
  48. callBacks.clear();
  49. _lockList = false;
  50. }
  51. }