搜索插件、代码仓与 APP 分类

插件详情v2.0.0

simple_observable

使用 Future、Stream 和/或回调观察值的变化。

AndroidiOSWebmacOSWindowsLinux
近 30 天下载
19.9万
喜欢数
6
Pub 分数
160

安装插件

flutter pub add simple_observable

插件介绍

基于插件公开信息、社区数据与项目使用情况整理的选型参考。

simple_observable 是一个轻量级的 Dart 包,可通过 Futures、Streams 或回调轻松观察值的变化。它通过提供简洁的接口来响应数据更新,从而简化了响应式编程,无需编写样板代码。非常适合用于 Flutter 应用中的状态管理,支持 Android、iOS、Web、macOS、Windows 和 Linux 等多个平台。该包通过减少跟踪异步数据流的复杂性,提升了开发者的生产力。

适合场景

  • 实时数据更新
  • Flutter 应用中的状态管理
  • 事件驱动的UI更新
  • 处理异步数据流
  • 简化回调逻辑

主要特点

  • 支持 Futures 和 Streams
  • 基于回调的观察
  • 最小化样板代码
  • 跨平台兼容性
  • 与现有代码的轻松集成

适合对象

  • 寻求简单状态更新的开发者
  • 具有响应式 UI 的 Flutter 应用需要
  • 避免使用复杂状态管理方案的项目
  • 注重代码简洁性的团队
  • 需要轻量级可观测性的应用

使用建议

  • 不适合复杂的状态树
  • 限于基本观察模式
  • 无内置的持久化或撤销功能
  • 最适合中小型应用
  • 需要手动处理订阅

原始 README

以下为关联源码仓库的 README 原文快照,最新内容请访问源码仓库。

pub.dev

simple_observable

Observe value changes using a Future, Stream, and/or a callback.

Source

class Observable<T> {
  Observable({T initialValue, this.onChanged, this.checkEquality = true})
      : _value = initialValue;

  /// If true, setting the [value] will only notifiy if the new value is different
  /// than the current value.
  final bool checkEquality;
  final void Function(T value) onChanged;

  var _completer = Completer<T>();

  bool _canceled = false;
  bool get canceled => _canceled;

  T _value;

  /// The current value of this observable.
  T get value => _value;
  set value(T val) {
    if (!canceled && (!checkEquality || _value != val)) {
      _value = val;
      // Delaying notify() allows the Future and Stream to update correctly.
      Future.delayed(Duration(microseconds: 1), () => notify(val));
    }
  }

  /// Alias for [value] setter. Good for passing to a Future or Stream.
  void setValue(T val) => value = val;

  @protected
  @mustCallSuper
  void notify(T val) {
    if (onChanged != null) onChanged(val);
    // Completing with a microtask allows a new completer to be constructed
    // before listeners of [nextValue] are called, allowing them to listen to
    // nextValue again if desired.
    _completer.complete(Future.microtask(() => val));
    _completer = Completer<T>();
  }

  Future<T> get nextValue => _completer.future;
  Stream<T> get values async* {
    while (!canceled) {
      yield await nextValue;
    }
  }

  /// Permanently disables this observable. Further changes to [value] will be
  /// ignored, the outputs [onChanged], [nextValue], and [values] will not be
  /// called again.
  @mustCallSuper
  void cancel() => _canceled = true;
}

所属分类

依赖

依赖清单 1 项

源码仓库

使用此插件的项目