Flutter学习(六)EventBus的使用

背景

项目开发过程中,有些场景,需要跨页面进行数据传递。按照安卓开发的思路,在flutter实现一个事件总线EventBus,进行数据传递

原理

通过dart的签名函数,进行监听集合设置,然后post分发的时候,进行集合遍历,回调,实现事件传递。

实现过程

总体思路,就是通过一个订阅,取消订阅,遍历订阅对象,进行数据传递。

下面直接上代码:

复制代码
//发布者接口
import 'package:ftplayer/common/utils/LogUtils.dart';

abstract class IPublisher {
  void post<T>(T event);
}

//订阅者:函数对象
typedef ISubscriber<T> = void Function(T event);

//集中式通信,
//1.IEventBus继承IPublisher,分发数据
//2.IEventBus注册和取消注册ISubscriber
abstract class IEventBus extends IPublisher {
  void register<T>(ISubscriber<T> subscriber);

  void unregister<T>(ISubscriber<T> subscriber);
}

Type typeOf<T>() => T;

class XEventBus implements IEventBus {
  //我们用map存放我们的订阅者。不同订阅者订阅的Event类型可能是不同的
  Map<Type, List<Function>> map = {};

  @override
  void register<T>(ISubscriber<T> subscriber) {
    Type type = typeOf<T>();
    if (!map.containsKey(type)) {
      map[type] = [];
    }
    map[type]?.add(subscriber);
  }

  @override
  void unregister<T>(ISubscriber<T> subscriber) {
    Type type = typeOf<T>();
    if (map.containsKey(type)) {
      map[type]?.remove(subscriber);
    }
  }

  //发布
  @override
  void post<T>(T event) {
    Type type = typeOf<T>();
    if (map.containsKey(type)) {
      var subscribers = map[type];
      subscribers?.forEach((subscriber) => subscriber.call(event));
    }
  }
}

//外部调用方法
class EventBusProvider {
  static final EventBusProvider _instance = EventBusProvider._internal();
  XEventBus _singleEventBus = XEventBus();

  factory EventBusProvider() {
    return _instance;
  }

  EventBusProvider._internal();

  XEventBus singleEventBus() {
    return _singleEventBus;
  }

  XEventBus newEventBus() {
    return XEventBus();
  }
}

调用

复制代码
late ISubscriber<LoginStatusEvent> loginSub;

 loginSub = (event) {
     loginStatus(event);
 };

 _eventBus.register(loginSub);


 _eventBus.unregister(loginSub);


getEventBus().post(LoginStatusEvent(fromPageType: 0));

上述代码中,getEventBus()就是获取的EventBus对象,这里可以是单例,或者是new多个对象。主要看项目的情况决定。

that's all----------------------------------------------------------------

相关推荐
好望角雾眠11 小时前
第一阶段C#基础-10:集合(Arraylist,list,Dictionary等)
笔记·学习·c#
艾伦~耶格尔11 小时前
【集合框架LinkedList底层添加元素机制】
java·开发语言·学习·面试
星仔编程12 小时前
python学习DAY46打卡
学习
大霞上仙12 小时前
实现自学习系统,输入excel文件,能学习后进行相应回答
python·学习·excel
yatingliu201914 小时前
HiveQL | 个人学习笔记
hive·笔记·sql·学习
武当豆豆14 小时前
C++编程学习(第25天)
开发语言·c++·学习
风和日丽 随波逐流14 小时前
java17学习笔记-Deprecate the Applet API for Removal
笔记·学习
淮北也生橘1214 小时前
Linux的ALSA音频框架学习笔记
linux·笔记·学习
diablobaal15 小时前
云计算学习100天-第17天
学习
果粒橙_LGC15 小时前
论文阅读系列(一)Qwen-Image Technical Report
论文阅读·人工智能·学习