如何在 Flutter 中将事件从一个有状态小部件广播到另一个有状态小部件

2023-12-08

我想将事件从一个有状态小部件广播到另一个有状态小部件,但似乎找不到一种方法。我安装了这个插件: event: ^1.1.4 但它没有触发。我想要如下所示的东西:

Stateful Widget 1:
SomeEventClass.broadcastEvent();

Stateful Widget 2:
SomeEventClass.subscribe();

通过使用这样的东西。

class ContinuousStream {
  _DataStore _mStorage = _DataStore.getInstance();

  /// Sets a new value [value] to the data stream [stream].
  /// If there are active subscribers, the value will be dispatched to them.
  void emit(String stream, var value) {
    _mStorage?.setValue(stream, value);
  }

  /// Subscribes to the given stream [stream].
  /// If stream already has data set, it will be delivered to the [callback] function.
  void on(String stream, void Function(Object) callback) {
    _mStorage?.setCallback(stream, callback);
  }

  /// Returns the current value of a given data [stream].
  Object getValue(String stream) {
    return _mStorage?.getValue(stream);
  }
}

// Storage class for ContinuousStream.
class _DataStore {
  // Singleton Instance for DataStore
  static _DataStore _instance;

  // Map instance to store data values with data stream.
  HashMap<String, _DataItem> _mDataItemsMap = HashMap();

  // Sets/Adds the new value to the given key.
  void setValue(String key, var value) {
    // Retrieve existing data item from map.
    _DataItem item = _mDataItemsMap[key];

    item ??= _DataItem();

    // Set new value to new/existing item.
    item.value = value;

    // Reset item to the map.
    _mDataItemsMap[key] = item;

    // Dispatch new value to all callbacks.
    item.callbacks?.forEach((callback) {
      callback(value);
    });
  }

  // Sets/Adds the new callback to the given data stream.
  void setCallback(String key, Function(Object) callback) {
    if (callback != null) {
      // Retrieve existing data item from the map.
      _DataItem item = _mDataItemsMap[key];

      item ??= _DataItem();

      // Retrieve callback functions from data item.
      List<Function(Object)> callbacks = item.callbacks;

      // Check if callback functions exists or not.
      if (callbacks == null) {
        // If it's null then create new List.
        callbacks = List();

        // Set callback functions list to data item.
        item.callbacks = callbacks;

        // Set the data item to the map.
        _mDataItemsMap[key] = item;
      }

      // Add the given callback into List of callback functions.
      callbacks.add(callback);

      // Dispatch value to the callback function if value already exists.
      if (item.value != null) {
        callback(item.value);
      }
    }
  }

  // Returns current value of the data stream.
  Object getValue(String key) {
    return _mDataItemsMap[key].value;
  }

  // Returns singleton instance of _DataStore
  static _DataStore getInstance() {
    _instance ??= _DataStore();
    return _instance;
  }
}

// Data class to hold value and callback functions of a data stream.
class _DataItem {
  var value;
  List<Function(Object)> callbacks;
}

创建此类后,您就可以初始化并访问流。例如,这需要在 StateFulWidget 1 和 StateFUlWidget 2 中完成。

ContinuousStream continuousStream = new ContinuousStream();

然后从 StateFulWidget1 开始:

void send() {
      String message = "Hello";
      continuousStream.emit("chat-message", message);
  }

这对应于您的广播事件。

来自 StatefulWidget2:

continuousStream.on("chat-message", (message) {
      print("Message Received: $message");
    });

这对应于您的订阅事件。 这应该可以解决你的问题。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何在 Flutter 中将事件从一个有状态小部件广播到另一个有状态小部件 的相关文章

随机推荐

  • 自动增量,但忽略列中的现有值

    我有一张桌子 create table DB t1 id SERIAL name varchar 255 并插入一些数据 insert into DB t1 name values name1 insert into DB t1 id na
  • 如何从 SQL*Plus 查询中删除空格?

    从 sqlplus 调用的下面的查询在每个值的末尾返回很多空格 我该如何删除它 请参阅下面的示例 我用 x 替换了这些值 x x x x
  • 每个 python 对象一个 int [重复]

    这个问题在这里已经有答案了 可能的重复 类实例的自动递增 ID 我想要类似以下 Python 中的 Java 类 public class MyObject private static int ID 0 private final int
  • 在Python中获取索引的默认值超出范围[重复]

    这个问题在这里已经有答案了 a 123 2 4 b a 4 or sss print b 当列表索引超出范围时 我想获得默认值 此处 sss 我怎样才能做到这一点 本着 请求宽恕 而不是许可 的 Python 精神 这里有一种方法 try
  • Bootstrap 视频大屏幕

    我正在尝试制作一个视频来覆盖 bootstrap Jumbotron 但没有成功 这似乎是一件非常简单的事情 但我尝试的一切似乎都失败了 我已经尝试过发布的解决方案here没有成功 我也尝试过将视频的位置设置为绝对位置 并将所有边设置为 0
  • CSS 渐变动画

    我正在尝试按照所述设置 CSS 渐变动画here但我无法让它工作 作为一个例子 我已经放在一起thisjsfiddle 总的来说 CSS 渐变过渡似乎不起作用 div Machine webkit transition background
  • 在 mongoose + nodeJS 中检测到循环依赖

    我收到如下错误 错误 检测到循环依赖性 在serializeObject F Full Stack course code base meanhotel node modules bson lib bson parser serialize
  • 在多索引数据帧上突出显示最大/最小值 - Pandas

    假设有一个 2 层 MultiIndex 数据框 df pd DataFrame one A 100 3 two A 101 4 three A 102 6 one B 103 6 two B 104 0 three B 105 3 col
  • 子类构造函数中的堆栈溢出错误[重复]

    这个问题在这里已经有答案了 我的超类是 public abstract class MarketProduct private String name public MarketProduct String productName name
  • Python + Github REST API:更新文件内容请求的问题

    我从以下网站获得 Status 400更新文件内容Github API 即使 400 不在可能的列表中HTTP 响应状态 我的问题是content密钥需要进行 Base64 编码 但是 当我将内容转换为 base64 时 API 会响应 解
  • MVVMCross 中的自定义插件

    我正在开发 MVVMCross v3 我想创建自己的插件 我遵循了本教程 适用于 vNext http slodge blogspot fr 2012 10 build new plugin for mvvmcrosss html 为了兼容
  • 如何从简单的 json 制作所需的 json 树

    我在转换简单时遇到问题json into json tree 我需要遵循的步骤是 发现父母有pid 0会有一些 id 5a016637e986c90418e96ee9 上面发现 id 5a016637e986c90418e96ee9 as
  • 如何从 Gmail 的主收件箱中获取未读邮件?

    我在我的应用程序中使用 Javascript 客户端 API 并尝试从主收件箱获取未读邮件 如果我在请求标签时使用收件箱和未读名称 我会从所有标签中获取所有未读邮件 没有其他标签类型名称有效 我已经在 API 资源管理器中进行了实验 但我似
  • 尽管文件已被另一个程序更改,但 fread 未读取更新的值

    有两个程序同时处理我的特殊文件 他们有一个共同的起点 define TASK POSITION 0x0100 include
  • Swing 中自动增大字体大小

    I would like to know if there are methods of automatically increasing the font size based on the size of a component I h
  • 检索变量声明

    当我几百岁的时候 我怎样才能找到我是如何第一次声明某个变量的 从我第一次声明的地方开始 例如 我声明了以下内容 a lt c vectorA vectorB vectorC 现在我想看看我是如何声明的 我怎样才能做到这一点 谢谢 您可以尝试
  • 参数化 pytest 夹具

    据我从有关 pytest 夹具参数化的文档中了解到 它使用给定的参数创建夹具的副本 从而调用需要具有不同副本的夹具的每个测试 我的需求有点不同 假设有一个固定装置 pytest fixture def sample foo return F
  • “svn:externals”有什么好处?

    如果我没有遇到过 我就不会了解 svn externals这一页 所以 我设置了我的工作文件夹 然后 mkdir lib vendor svn add parents lib vendor svn ps svn externals symf
  • 用于检测浏览器功能/插件的 JavaScript 库

    我正在尝试找到一个 最好是开源的 JS 库来确定尽可能多的有关用户 Web 浏览器环境的信息 我知道可以获得以下数据 屏幕分辨率 User Agent Accept Language 和其他首选项通常在 HTTP 标头中发送 安装的插件 通
  • 如何在 Flutter 中将事件从一个有状态小部件广播到另一个有状态小部件

    我想将事件从一个有状态小部件广播到另一个有状态小部件 但似乎找不到一种方法 我安装了这个插件 event 1 1 4 但它没有触发 我想要如下所示的东西 Stateful Widget 1 SomeEventClass broadcastE