패키지, 저장소 및 앱 카테고리 검색

패키지 상세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 개

소스 저장소

이 패키지를 사용하는 프로젝트

아직 데이터가 없습니다.