Flutter跨组件通讯event_bus

Flutter中经常使用event_bus实现跨页面传递数据,其核心是基于Dart Streams(流)。event_bus是一个典型的采用订阅发布模式设计,包含发布者和订阅者两种角色,可以通过事件总线来触发事件和监听事件。

使用

安装

event_bus: ^1.1.0

创建EventBus

import 'package:event_bus/event_bus.dart';
/// 创建EventBus
EventBus eventBus = EventBus();

定义事件UpdateAppEvent

/// 更新App版本事件
class UpdateAppEvent {

  final String from;
  final String version;
  final String title;
  final List description;
  final bool forcedUpdate;
  final String link;

  UpdateAppEvent(this.from, this.version, this.title, this.description, this.forcedUpdate, this.link);

  @override
  String toString() {
    return "UpdateAppEvent {from: $from, version: $version, title: $title, description: $description, forcedUpdate: $forcedUpdate, link: $link}";
  }
}

注册事件监听器

import 'dart:async';

   /// 监听版本检查事件
 StreamSubscription  _busSubscription =  eventBus.on().listen((event) {
      updateAppDialog.show(context, event);
    });

触发订阅的事件

 eventBus.fire(
      UpdateAppEvent(
        pageHome,
        remoteVersion,
        title,
        remoteDescription,
        forcedUpdate,
        link,
      ),
    );

销毁已订阅事件

  @override
  void dispose() {
    _busSubscription.cancel();
    super.dispose();
  }

你可能感兴趣的:(Flutter跨组件通讯event_bus)