fast_notification.dart 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899
  1. ///
  2. /// fast_notification.dart
  3. /// fast_app
  4. /// Created by qiuguian on 2019/10/21.
  5. /// Copyright © 2019 fastapp. All rights reserved.
  6. ///
  7. /// website: http://www.fastapp.top
  8. ///
  9. import 'package:flutter/material.dart';
  10. typedef Callback(data);
  11. class FastNotification {
  12. FastNotification._();
  13. static final _eventMap = <String, List<Callback>>{};
  14. static Callback addListener(String event, Callback call) {
  15. var callList = _eventMap[event];
  16. if (callList == null) {
  17. callList = new List();
  18. _eventMap[event] = callList;
  19. }
  20. callList.add(call);
  21. return call;
  22. }
  23. static removeListenerByEvent(String event) {
  24. _eventMap.remove(event);
  25. }
  26. static removeListener(Callback call) {
  27. final keys = _eventMap.keys.toList(growable: false);
  28. for (final k in keys) {
  29. final v = _eventMap[k];
  30. final remove = v.remove(call);
  31. if (remove && v.isEmpty) {
  32. _eventMap.remove(k);
  33. }
  34. }
  35. }
  36. static once(String event, {data}) {
  37. final callList = _eventMap[event];
  38. if (callList != null) {
  39. for (final item in new List.from(callList, growable: false)) {
  40. removeListener(item);
  41. _errorWrap(event, item, data);
  42. }
  43. }
  44. }
  45. static push(String event, [data]) {
  46. var callList = _eventMap[event];
  47. if (callList != null) {
  48. for (final item in callList) {
  49. _errorWrap(event, item, data);
  50. }
  51. }
  52. }
  53. static _errorWrap(String event, Callback call, data) {
  54. try {
  55. call(data);
  56. } catch (e) {}
  57. }
  58. }
  59. mixin FastNotificationStateMixin<T extends StatefulWidget> on State<T> {
  60. List<Callback> _listeners;
  61. void notice(String event, Callback call) {
  62. _listeners ??= new List();
  63. _listeners.add(FastNotification.addListener(event, call));
  64. }
  65. void noticeDel(Callback call) {
  66. if (_listeners.remove(call)) {
  67. FastNotification.removeListener(call);
  68. }
  69. }
  70. void noticeDelAll() {
  71. _listeners?.forEach(FastNotification.removeListener);
  72. _listeners?.clear();
  73. }
  74. @override
  75. void dispose() {
  76. noticeDelAll();
  77. super.dispose();
  78. }
  79. }