搜尋套件、儲存庫與 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 項

原始碼儲存庫

使用此套件的專案

暫無相關資料。