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

插件详情v1.0.0

cached_value

一种简单的方法,用于缓存那些来自开销较大的操作的值。

AndroidiOSWebmacOSWindowsLinux
近 30 天下载
1.1万
喜欢数
25
Pub 分数
160

安装插件

flutter pub add cached_value

插件介绍

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

cached_value 是一个轻量级的 Flutter/Dart 包,提供了一种简单的方式来缓存由昂贵操作派生的值。它确保一旦值被计算,就会被存储并重复使用,而无需重新计算,从而提高性能并降低延迟。该包支持异步操作,并可配置过期时间自动处理缓存。适用于 API 响应、复杂计算或数据解析等场景,避免重复计算。

适合场景

  • 缓存 API 响应
  • 存储计算结果
  • 减少冗余数据处理
  • 提高应用程序的响应速度
  • 管理昂贵的初始化任务
  • 保留临时状态

主要特点

  • 简单的异步缓存
  • 可配置的过期时间
  • 到期后自动重新计算
  • 支持空安全值
  • 轻量且依赖极少
  • 跨平台兼容性

适合对象

  • 寻求简单缓存的开发者
  • 频繁进行昂贵计算的应用程序
  • 性能优化项目
  • 带有缓存数据的状态管理
  • 快速缓存解决方案原型设计

使用建议

  • 不适用于大型数据集
  • 没有内置的跨应用重启持久化
  • 在某些情况下需要手动清除缓存
  • 限制为内存存储
  • 最适合短暂缓存的值
  • 不支持复杂的缓存策略

原始 README

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

cached_value

Pub

A simple way to cache values that result from rather expensive operations.

It is useful to cache values that:

  • Are computed from other values in a consistent way;
  • Can be changed given known and unknown conditions;
  • Should not be computed on every access (like a getter);

A cached_value is better used over imperative APIs, such as Flutter's render objects. See Motivation for more.

Installation

Add to pubspec.yaml:

dart pub add cached_value

Usage

A cache can start as a simple manually controlled cache and then be enhanced with automatic functionalities such as dependencies and time-to-live (TTL).

1.Creating a simple cached that is invaldiated manually
  int factorial(int n) {
    if (n < 0) throw ('Negative numbers are not allowed.');
    return n <= 1 ? 1 : n * factorial(n - 1);
  }

  int originalValue = 1;
  final factorialCache = CachedValue(() => factorial(originalValue));
  print(factorialCache.value); // 1

  originalValue = 6;

  print(factorialCache.value); // 1
  print(factorialCache.isValid) // true, invalid only when invalidate is called
  
  // mark as invalid
  factorialCache.invalidate();
  print(factorialCache.isValid); // false

  print(factorialCache.value); // 720
  print(factorialCache.isValid); // true

Accessing value when the cache is invalid refreshes the cache. It can be refreshed manually via the refresh method:

  // ...
  originalValue = 12;
  factorialCache.refresh();

  print(factorialCache.value); // 12
2. Adding dependencies

A dependent cache is marked as invalid if its dependency value has changed.

  int factorial(int n) {
    if (n < 0) throw ('Negative numbers are not allowed.');
    return n <= 1 ? 1 : n * factorial(n - 1);
  }
  
  int originalValue = 1;
  final factorialCache = CachedValue(
      () => factorial(originalValue),
  ).withDependency(() => originalValue);
  print(factorialCache.value); // 1
  print(factorialCache.isValid); // true
  
  // update value
  originalValue = 6;
  print(factorialCache.isValid); // false

  print(factorialCache.value); // 720
  print(factorialCache.isValid); // true

⚠️Important: The dependency callback is called on every value access. So it is recommended to keep it as declarative as possible.

final someCache = CachedValue(
  // ...
  ).withDependency(
    () => someExpensiveOperation(originalValue), // ❌ Avoid this:
  );
3. Adding time to live (TTL)

A cache can be automatically marked as invalid some time after a refresh.

    int factorial(int n) {
        if (n < 0) throw ('Negative numbers are not allowed.');
        return n <= 1 ? 1 : n * factorial(n - 1);
    }
  
    int originalValue = 1;
    final factorialCache = CachedValue(
      () => factorial(originalValue),
    ).withTimeToLive(
      lifetime: Duration(seconds: 3),
    );
    
    originalValue = 6;
    
    print(factorialCache.value); // 1
    
    await Future.delayed(Duration(seconds: 3));
    
    print(factorialCache.value); // 720

More docs

There is more detailed docs on the API documentation.

Motivation

Some imperative APIs such as the canvas paint on Flutter render objects of Flame's components may benefit from values that can be stored and reused between more than a single frame (or paint).

In some very specific cases, I found very convenient to store some objects across frames, like Paint and TextPainter instances.

Example on a render object:

class BlurredRenderObject extends RenderObject {

  // ...

  double _blurSigma = 0.0;
  double get blurSigma => _blurSigma;
  set blurSigma(double value) {
    _blurSigma = blurSigma;
    markNeedsPaint();
  }

  // ...

  @override
  void paint(PaintingContext context, Offset offset) {
    final canvas = context.canvas;


    final paint = Paint()..maskFilter = MaskFilter.blur(
        BlurStyle.normal, blurSigma
    );
    canvas.drawRect(Rect.fromLTWH(0, 0, 100, 100), paint);
  }
}

Can be changed to:

class BlurredRenderObject extends RenderObject {

  // ...

  double _blurSigma = 0.0;
  double get blurSigma => _blurSigma;
  set blurSigma(double value) {
    _blurSigma = blurSigma;
    markNeedsPaint();
  }

  // Add cache:
  late final paintCache = CachedValue(
     () => Paint()..maskFilter = MaskFilter.blur(BlurStyle.normal, blurSigma),
  ).withDependency(() => blurSigma);

  // ...

  @override
  void paint(PaintingContext context, Offset offset) {
    final canvas = context.canvas;

    // use cache:
    final paint = paintCache.value;
    canvas.drawRect(Rect.fromLTWH(0, 0, 100, 100), paint);
  }
}

所属分类

依赖

依赖清单 2 项

源码仓库

使用此插件的项目

暂无相关数据。