美文网首页
flutter广播EventBus

flutter广播EventBus

作者: xiaotimel | 来源:发表于2021-01-16 11:51 被阅读0次

在flutter本身没有提供类似于android的广播通信机制。要想实现广播刷新页面,我们可以使用强大的EventBus

EventBus

https://pub.dev/packages/event_bus/example
EventBus的使用很简单
1、添加eventbus的依赖库

dependencies:
  flutter:
    sdk: flutter

  event_bus: ^1.1.1

2、创建eventbus

import 'package:event_bus/event_bus.dart';

///event bus
class EventBusUtils {
   static EventBus _eventBus;

  static EventBus getInstance() {
    if (_eventBus == null) {
      _eventBus = EventBus();
    }
    return _eventBus;
  }
}

3、创建发送的事件

class TestEvent{
  String msg;
  int state;

  TestEvent(this.msg,this.state);
}

4、在页面监听事件发送

  @override
  void initState() {
    super.initState();
    EventBusUtils.getInstance().on<TestEvent>().listen((event) {
      print("event bus msg is ="+event.msg +"   state info is  = "+event.state.toString());
    });
  }

  @override
  void dispose() {
    super.dispose();
    EventBusUtils.getInstance().destroy();
  }

在on后的泛型表示要监听的事件,如果发送的不是这个类型的事件是无法接收到的。
5、发送事件

EventBusUtils.getInstance().fire(TestEvent("你是猪么", 200));

相关文章

网友评论

      本文标题:flutter广播EventBus

      本文链接:https://www.haomeiwen.com/subject/njlnaktx.html