Flutter widget 间传递数据的方案 InheritedWidget、Notification、EventBus

Flutter是由众多widget构成的UI框架,之前的文章我们在不同的widget之间传递数据是通过构造函数传参的方式传递。如果嵌套的widget过多,这么写不免有些麻烦且层级复杂。所以Flutter还提供了其他方案来实现跨 widget 间数据的传递,下面就介绍InheritedWidget、Notification 和 EventBus这三种方案。

InheritedWidget

InheritedWidgetwidget的基类,可有效地向下传播信息。
可以理解为子 widget可以在任何位置获取继承了InheritedWidget父 widget中的数据。

示例

示例中通过构造函数和继承InheritedWidget两种方式实现父 widget :FrogColor子 widget:FColor传值。

构造函数传值:

在这里插入图片描述

继承 InheritedWidget 传值:
  1. 首先定义一个类FrogColor继承InheritedWidget,并在构造方法中传递数据和方法:model 和 doSomeThing
class FrogColor extends InheritedWidget {

  const FrogColor({
    Key key,
    @required this.model,
    @required this.doSomeThing,
    @required Widget child,
  }) : assert(model != null),
        assert(child != null),
        super(key: key, child: child);

  // 直接从 _FirstPageState 中的 State 获取数据,这里可指定为泛型
  final _FirstPageState model;
  // 方法
  final Function() doSomeThing;

  // 获取实例
  static FrogColor of(BuildContext context) {
    return context.dependOnInheritedWidgetOfExactType<FrogColor>();
  }

  // 判断是否需要更新
  @override
  bool updateShouldNotify(FrogColor old) => model != old.model;
}
  1. 在布局中使用FrogColor包裹FColorwidget,同时传递data和 doSomeThing 方法。由于上面定义的data_FirstPageState所以这里直接传递thisdoSomeThing方法中我们传递了_changeColor用于改变mColor的值,并且在子布局中能够刷新显示最新的color
    在这里插入图片描述
  2. 最后我们在FColor中获取到FrogColor中的date数据和调用doSomeThing 方法
    在这里插入图片描述

上面的FrogColormodel是直接传入_FirstPageState,这样耦合度会比较高
所以我们将这个对象转为泛型,封装后如下:

新建 state_provider.dart文件:

import 'package:flutter/material.dart';

/// 使用泛型传入数据
class IProvider<T> extends InheritedWidget {
  // 数据
  final T data;
  // 方法
  final Function() doSomeThing;

  IProvider({Key key, Widget child, this.data,  this.doSomeThing})
      : super(key: key, child: child);

  @override
  bool updateShouldNotify(IProvider oldWidget) {
    return data != oldWidget.data;
  }
  static IProvider<T> of<T>(BuildContext context) {
    return context.dependOnInheritedWidgetOfExactType<IProvider<T>>();
  }
}

封装好的使用需要传入数据类

@override
Widget build(BuildContext context) {

  return Scaffold(
      appBar: AppBar(
        title: Text('InheritedWidget'),
      ),
      body: IProvider<_FirstPageState>(// 传入 _FirstPageState
        data: this
        doSomeThing: _changeColor,//提供修改数据的方法
        child: FColor('哈哈哈'),
      )
  );
}

以上就是InheritedWidget的使用,使用InheritedWidget的方式可以降低数据和UI界面的耦合。
直接使用InheritedWidget不免有些麻烦,Flutter提供了更加强大的 Provider 库,用于实现依赖注入和状态管理(后续了解之后详细介绍)。

InheritedWidget仅限与从父widget向下传递数据。那么从子widget向上传递数据如何实现呢?Notifiation就可以实现。

Notification

Notification 数据共享方式是从子 widgetw 向上传递至父widget`。

在之前的文章 Flutter 嵌套滚动 CustomScrollView 示例 中,我们使用NotificationListener去监听子child CustomScrollView的滑动距离。

同理,将子widget的数据传递给父widget也可以用这个方式实现

示例

从子widget向上发送数据,在父widget中监听到消息并打印在控制台。
在这里插入图片描述
在这里插入图片描述
以上就是Notification的使用,使用Notification的方式可以子widget的数据通过dispatch发送给父widget
无论是 InheritedWidget还是 Notificaiton,都需要依赖与父子关系的widget
而一些场景下的数据传递是没有这层关系的,
Android中有事件总线的方式可以很方便的实现这类场景的数据传递,
Flutter中也有这样类似的库:EventBus

EventBus

使用Dart Streams进行应用程序解耦的简单事件总线。

示例
  1. 引入库
dependencies:
  event_bus: ^1.1.1
  1. 初始化EventBus,并定义消息数据类
final eventBus = new EventBus();

/// 传递的数据
class MsgEvent{
  final String msg;
  MsgEvent(this.msg);
}
  1. 监听
 // 监听数据变化
eventBus.on<MsgEvent>().listen((event) {
   print("接收到的数据:${event.msg}");
 });
  1. 发送数据
 eventBus.fire(MsgEvent("子 widget 发送过来的数据:老头子"));

通过以上的4步即可完成不依赖widget的数据传输。

示例完整源码
import 'package:event_bus/event_bus.dart';
import 'package:flutter/material.dart';

final eventBus = EventBus();

class FirstPage extends StatefulWidget {
  @override
  _FirstPageState createState() {
    return _FirstPageState();
  }
}

class _FirstPageState extends State<FirstPage> {

  @override
  void initState() {
    super.initState();
    // 监听数据变化
    eventBus.on<MsgEvent>().listen((event) {
      print("接收到的数据:${event.msg}");
    });
  }

  @override
  void dispose() {
    super.dispose();
    // 释放资源
    eventBus.destroy();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: AppBar(
          title: Text('EventBus'),
        ),
        body: Column(
          mainAxisAlignment: MainAxisAlignment.start,
          crossAxisAlignment: CrossAxisAlignment.start,
          children: <Widget>[
            // 子 widget
            RaisedButton(
              // 按钮点击时分发通知
              onPressed: () {
                eventBus.fire(MsgEvent("父 widget 发送过来的数据:我是你爸爸"));
              },
              child: Text("父 widget 发送数据"),
            ),
            CustomChild(),
          ],
        ));
  }
}

class CustomChild extends StatelessWidget {

  @override
  Widget build(BuildContext context) {
    return RaisedButton(
      // 按钮点击时分发通知
      onPressed: () {
        eventBus.fire(MsgEvent("子 widget 发送过来的数据:老头子"));
      },
      child: Text("子 widget 发送数据"),
    );
  }
}

/// 消息数据类
class MsgEvent{
  final String msg;
  MsgEvent(this.msg);
}

wan~

  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

_龙衣

赏杯快乐水喝喝

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值