• Flutter Event 派发


    在 其他前端开发中,为了解耦 会使用事件中心,进行事件的派发; Flutter中 也可以这么操作;

    但是呢 插件市场有个叫  event_bus 的;感觉不怎么好用!

    所在照着以前的思路;搬了一个!

    参考:https://www.jianshu.com/p/d036ed61f1c8 ;但是估计是个老版本的;

    这边优化了一下 如下:

    1. typedef void EventCallback(arg);
    2. class AppEvent {
    3. static final AppEvent _instance = AppEvent._internal();
    4. AppEvent._internal();
    5. factory AppEvent() {
    6. return _instance;
    7. }
    8. //保存事件订阅者队列,key:事件名(id),value: 对应事件的订阅者队列
    9. final _eMap = <dynamic, List>{};
    10. //添加订阅者
    11. void on(eventName, EventCallback callBack) {
    12. if (eventName == null) return;
    13. if (!_eMap.containsKey(eventName)) {
    14. _eMap.addEntries({eventName: []}.entries);
    15. }
    16. _eMap[eventName]?.add(callBack);
    17. }
    18. //移除订阅者
    19. void off(eventName, {EventCallback? callBack}) {
    20. var list = _eMap[eventName];
    21. if (eventName == null || list == null) return;
    22. if (callBack == null) {
    23. // _eMap[eventName] = null;
    24. _eMap[eventName]?.clear();
    25. } else {
    26. list.remove(callBack);
    27. }
    28. }
    29. //触发事件,事件触发后该事件所有订阅者会被调用
    30. void emit(eventName, [arg]) {
    31. var list = _eMap[eventName];
    32. if (list == null) {
    33. print('**没有找打对应的订阅方法$eventName');
    34. return;
    35. }
    36. int len = list.length - 1;
    37. //反向遍历,防止订阅者在回调中移除自身带来的下标错位
    38. for (var i = len; i > -1; --i) {
    39. list[i](arg);
    40. }
    41. }
    42. }

    • 添加监听:
      1. AppEvent().on('pageReport-examine', (arg) {
      2. print('>>>>>收到消息$arg');
      3. setState(() {
      4. _examineListSelect.add(arg);
      5. });
      6. });

    • 取消监听:
      AppEvent().off('pageReport-examine');

    • 触发函数:
      1. AppEvent().emit(
      2. 'pageReport-examine',
      3. {
      4. 'id': '110',
      5. 'patrolRecordId': 'id',
      6. 'routeSubId': 'id',
      7. 'placeName': '测试节点',
      8. 'checkTime': '',
      9. 'isChecked': false,
      10. 'checkRecordInfo': {
      11. 'trouble': false,
      12. 'address': _locationResult?['address'],
      13. 'longitude': _locationResult?['latitude'],
      14. 'latitude': _locationResult?['longitude'],
      15. 'imgs': _selectPicture,
      16. 'voicePath': _selectAudio.isNotEmpty ? _selectAudio.first : '',
      17. 'bak': '',
      18. 'videoPath': _selectVideo.isNotEmpty ? _selectVideo.first : ''
      19. },
      20. },
      21. );

  • 相关阅读:
    js轮播图有,移入移出事件,左右滑动事件功能
    性能测试性能瓶颈问题分析调优案例
    详解AVL树(二叉搜索平衡树)【C++实现】
    在Elasticsearch IK分词器中更新、停用某些专有名词
    QT day2
    Java循环获取对象属性名称、属性值
    组播收数据问题,特定IP发来的数据包收不到,其余都可收到
    持续集成,持续交付和持续部署的概念,以及GitLab CI / CD的介绍
    go 分支与循环
    Unity与IOS⭐Xcode打包,上架TestFlight的完整教程
  • 原文地址:https://blog.csdn.net/nicepainkiller/article/details/125973947