Flutter事件总线event_bus

在Flutter中,一个页面可能有多个分离的组件组成

假设:我们有一个页面叫A,在A页面中引入了A1,A2,A3三个子页面,我们需要在A页面中调用A1页面中的弹出框或方法要怎么实现?

第一种方法 实例化对象,在A的页面中实例化A1去调用A1的弹出框组件,那这种方法一般不好实现,因为A1在init的时候可能要加载从A页面过来的数据和context,所以不推荐这样做。

那就可以用到event_bus

简介:

顾名思义 event->事件 bus->可以理解为总线,交给事件总线去做,可以大大的减少的耦合,只需要额外引入一个类去调用它,在被调用的方法的init中监听这个事件是否被调用然后去执行响应的方法即可。

图示:

实际操作

1、首先我们导包,创建一个名为ProductContentEvent的类去实例化Evenbus并在构造方法中传入一个str

import 'package:event_bus/event_bus.dart';

EventBus eventBus = new EventBus();

class ProductContentEvent{

  String str;
  ProductContentEvent(String str){
    this.str = str;
  }
}

2、在需要调用子组件的方法中调用上方实例化evenBus的fire方法

部分代码:

              Positioned(
                child: Container(
                  decoration: BoxDecoration(
                      color: Colors.white,
                      border: Border(
                          top: BorderSide(color: Colors.black26, width: 1))),
                  child: Row(
                    children: [
                      Container(
                        padding: EdgeInsets.only(
                            top: ScreenAdapter.height(5),
                            left: ScreenAdapter.width(20),right: ScreenAdapter.width(5)),
                        child: Column(
                          children: [Icon(Icons.shopping_cart), Text("购物车")],
                        ),
                      ),
                      Expanded(
                        flex: 1,
                        child: BuyButtonWidget(
                          color: Color.fromRGBO(253, 1, 0, 0.9),
                          text: "加入购物车",
                          cb: () {
                            eventBus.fire(ProductContentEvent("加入购物车"));
                          },
                        ),
                      ),
                      Expanded(
                        flex: 1,
                        child: BuyButtonWidget(
                          color: Color.fromRGBO(255, 165, 0, 0.9),
                          text: "立即购买",
                          cb: () {
                            eventBus.fire(ProductContentEvent("立即购买"));
                          },
                        ),
                      )
                    ],
                  ),
                ),
                width: ScreenAdapter.width(750),
                height: ScreenAdapter.width(100),
                bottom: 0,
              ),

3、在被调子类方的init方法中监听此eventbus

  @override
  void initState() {
    super.initState();
    _initAttr();
    _getSelectValue();
    //监听广播
    _actionEventBus = eventBus.on<ProductContentEvent>().listen((event) {
      print(event.str);
      //调用弹出框
      this._showMenuTabs();
    });
  }

猜你喜欢

转载自blog.csdn.net/u013600907/article/details/106250363
今日推荐