You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

关于Flutter异步库中AsyncCache类的定义及工作原理的技术咨询

Hey! Glad you're digging into Flutter's async libraries—AsyncCache is a real gem for avoiding redundant async work, so let's break it down clearly.

What is AsyncCache?

AsyncCache is a class built to cache the results of asynchronous operations (think API calls, database queries, or heavy computations). Its main job is to prevent you from running the same expensive async task multiple times unnecessarily, and it solves the common "thundering herd" problem where multiple parts of your app trigger the same task at once.

Core Definition & Key Components

At its heart, AsyncCache manages a cached result with a time-to-live (TTL) duration. Here are its critical parts:

  • Duration duration: The length of time the cached result stays valid. Once this time passes, the next call will re-run the async operation.
  • Internal cache storage: It tracks the latest successful result (and the ongoing Future while the task is running) so subsequent calls can reuse it instead of starting over.
  • Key methods:
    • Future<T> get(Future<T> Function() computation): The main method—it checks for a valid cached result, runs the provided computation if needed, and returns the result (cached or fresh).
    • void invalidate(): Manually clears the cached result, forcing the next get() call to run a fresh computation.
    • Future<T>? getIfPresent(): Returns the cached result if it's still valid, without triggering the computation at all.
How It Works (Step-by-Step)

Let's walk through the flow of using AsyncCache:

  1. First get() call: No cached result exists, so it runs your provided computation (the async task). It also stores the ongoing Future in its internal cache.
  2. Concurrent calls during computation: If another part of your app calls get() while the first task is still running, it will return the same Future instead of starting a new task—no duplicate work here.
  3. Computation completes: The result is stored in the cache along with a timestamp marking when it was saved.
  4. Calls within TTL: Any get() calls before the duration expires will immediately return the cached result, skipping the computation entirely.
  5. Calls after TTL expires: The cached result is considered stale, so AsyncCache runs the computation again, updates the cache, and returns the fresh result.
  6. Manual invalidation: If you call invalidate(), the cache is cleared right away—the next get() will trigger a brand-new computation.
Example Usage

Here's a practical example of using AsyncCache to cache a network request:

import 'package:async/async.dart';
import 'package:http/http.dart' as http;

// Create an AsyncCache with a 5-minute TTL
final userDataCache = AsyncCache<http.Response>(const Duration(minutes: 5));

Future<http.Response> fetchUserProfile(String userId) async {
  return userDataCache.get(() async {
    // This is the expensive async operation (API call)
    final response = await http.get(Uri.parse('https://api.example.com/users/$userId'));
    if (response.statusCode != 200) {
      throw Exception('Failed to load user profile');
    }
    return response;
  });
}

Even if fetchUserProfile is called 15 times in 3 minutes, it will only make one API call—all other calls will use the cached response.

Common Use Cases
  • Frequent API requests: Cache responses for data that doesn't change often (like user profiles, static app content).
  • Expensive local computations: Avoid re-running heavy tasks like parsing large JSON files or processing images multiple times.
  • Database queries: Cache query results to reduce load on your local database.

内容的提问来源于stack exchange,提问作者Vikash Kumar

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.29 00:47:34