flutter event_bus使用介紹


flutter中可以是用event_bus來消息通知
event_bus使用的是event_bus https://pub.dev/packages/event_bus 這個庫,這里只介紹如果使用該plugin,以及在使用的時候遇到的一些問題
本例demo下載地址:https://github.com/qqcc1388/flutter_event_bus
官方給出的使用方法:

創建消息對象
class UserLoggedInEvent {
  User user;

  UserLoggedInEvent(this.user);
}

創建eventBus
EventBus eventBus = EventBus();

注冊訂閱 這里可以將保存下來 dispose可以將該stream移除訂閱
StreamSubscription loginSubscription = eventBus.on<UserLoggedInEvent>().listen((event) {
  // All events are of type UserLoggedInEvent (or subtypes of it).
  print(event.user);
});


eventBus.on<UserLoggedInEvent>().listen((event) {
  // All events are of type UserLoggedInEvent (or subtypes of it).
  print(event.user);
});

發送消息
User user = {}; 
eventBus.fire(UserLoggedInEvent(user));

移除eventBus
  @override
  void dispose() {
    loginSubscription.cancel();
    super.dispose();
  }

主要注意的是 添加過訂閱后 一定要將訂閱steam移除,否則,頁面計算被移除,仍然可以接收到訂閱消息,造成內存泄漏

基於官方給的使用方法,對eventbus做了一層封裝,方便在項目中使用

import 'dart:async';
import 'package:event_bus/event_bus.dart';

typedef void EventCallback<T>(T event);

class EventBusUtils {
  factory EventBusUtils() => _getInstance();
  static EventBusUtils get instance => _getInstance();
  static EventBusUtils _instance;
  EventBusUtils._internal() {
    // 初始化
    _eventBus = new EventBus();
  }

  //初始化eventBus
  EventBus _eventBus;
  // EventBus get eventBus => _eventBus;

  /// 訂閱stream列表
  // List<StreamSubscription> subscriptionList;

  static EventBusUtils _getInstance() {
    if (_instance == null) {
      _instance = new EventBusUtils._internal();
    }
    return _instance;
  }

  /// 開啟eventbus訂閱 並
  StreamSubscription on<T>(EventCallback<T> callback) {
    StreamSubscription stream = _eventBus.on<T>().listen((event) {
      callback(event);
    });
    // subscriptionList.add(stream);
    return stream;
  }

  /// 發送消息
  void emit(event) {
    _eventBus.fire(event);
    
  }

  /// 移除steam
  void off(StreamSubscription steam) {
    steam.cancel();
  }
}

var eventBus = EventBusUtils.instance;

使用起來很很簡單

 var loginSuccessEvent;
  添加訂閱
  loginSuccessEvent = eventBus.on<UserLoggedInEvent>((event) {
    print('page A received msg');
    setState(() {
      params = event.userInfo;
    });
  });

 發送消息訂閱
 User user = {};
 eventBus.emit(UserLoggedInEvent(user));

  取消訂閱
   @override
  void dispose() {
    eventBus.off(loginSuccessEvent);
    super.dispose();
  }

封裝之后,使用變的簡化了

需要注意一點的是在使用event_bus的時候不要調用destroy()方法,否則將無法收到消息監聽,如果要移除訂閱,請使用 stream.cancel();


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM