Token导航 LogoToken导航TokenDH.com
前端设计需要联网github未标认证来源可访问许可证需确认审计通过

flutter-cachingFlutter caching 命令行

Agent Skill

flutter-caching 用于处理 GitHub 仓库、Issue、Pull Request 和代码协作信息,适合在 Codex、Claude、Cursor、Gemini CLI 中需要围绕仓库状态、代码变更或协作事项进行整理时使用。可结合来源仓库、安装命令和原始 README 继续核验具体用法。安装前建议确认权限范围、维护状态,以及是否会触发联网、命令执行或文件读写。

总安装

24,480

周安装

1,001

GitHub Stars

1,261

下载量

7,920
CodexClaudeCursorGemini CLI

安装说明

本站只整理中文说明和来源信息,不托管安装包,也不代用户安装。

GitHub

来源数

2

许可证

unknown

最后核验

2026-05-01

来源状态

来源可访问

安装方式

通过对话安装

复制提示词发给支持本地命令或 Skills 的 AI 助手,先确认命令和权限,再让它执行。

请帮我安装这个 Agent Skill:flutter-caching(Flutter caching 命令行)
来源仓库:https://github.com/flutter/skills
仓库路径:skills/flutter-caching
安装命令:
npx skills add https://github.com/flutter/skills --skill flutter-caching
安装前请先检查当前环境是否支持对应 CLI,并向我确认将要执行的命令、安装目录、联网范围和文件读写权限;确认后再执行。

命令行安装

复制命令到本机终端执行。该命令会通过 npx skills 从第三方来源获取 Skill;本站只展示命令,不托管安装包,也不自动执行。

skills.shnpx skills
npx skills add https://github.com/flutter/skills --skill flutter-caching

简介

跨多种数据类型和平台的 Flutter 应用程序的全面缓存和性能优化。

  • 提供决策逻辑来选择适当的缓存机制:内存中、shared_preferences
  • 用于键值对、用于关系数据的 SQLite、用于大 blob 的文件系统以及用于网络图像的图像缓存
  • 包括基于流的离线优先存储库模式,该模式首先生成缓存数据,然后从网络获取和更新
  • 涵盖 Android FlutterEngine 预热和缓存,以减少混合应用中的 Flutter 初始化延迟
  • 使用 ScrollCacheExtent 优化小部件渲染、图像缓存和滚动性能
  • 对象和严格的 GPU 内存限制
  • 通过参数化查询强制执行 SQL 注入预防,并验证性能反模式,例如不必要的 saveLayer()
  • 调用和小部件平等覆盖

SKILL.md

flutter-caching-and-performance

Goal

Implements advanced caching, offline-first data persistence, and performance optimization strategies in Flutter applications. Evaluates application requirements to select and integrate the appropriate local caching mechanism (in-memory, persistent, file system, or on-device databases). Configures Android-specific FlutterEngine caching to minimize initialization latency. Optimizes widget rendering, image caching, and scrolling performance while adhering to current Flutter API standards and avoiding expensive rendering operations.

Instructions

1. Evaluate and Select Caching Strategy (Decision Logic)

Analyze the user's data retention requirements using the following decision tree to select the appropriate caching mechanism:

  • Is the data temporary and only needed for the current session?

- *Yes:* Use In-memory caching.

  • Is the data small, simple key-value pairs (e.g., user preferences)?

- *Yes:* Use shared_preferences.

  • Is the data large, relational, or requires complex querying?

- *Yes:* Use On-device databases (e.g., sqflite). Proceed to Step 3.

  • Is the data large binary files, custom documents, or JSON blobs?

- *Yes:* Use File system caching (path_provider). Proceed to Step 2.

  • Is the data network images?

- *Yes:* Use Image caching (cached_network_image or custom ImageCache). Proceed to Step 6.

  • Is the goal to reduce Android Flutter UI warm-up time?

- *Yes:* Use FlutterEngine caching. Proceed to Step 5.

STOP AND ASK THE USER: "Based on your requirements, which data type and size are we handling? Should I implement SQLite, File System caching, or a different strategy?"

2. Implement File System Caching

When shared_preferences is insufficient for larger data, use path_provider and dart:io to persist data to the device's hard drive.

import 'dart:io';
import 'package:path_provider/path_provider.dart';

class FileCacheService {
  Future<String> get _localPath async {
    // Use getTemporaryDirectory() for system-cleared cache
    // Use getApplicationDocumentsDirectory() for persistent data
    final directory = await getApplicationDocumentsDirectory();
    return directory.path;
  }

  Future<File> get _localFile async {
    final path = await _localPath;
    return File('$path/cached_data.json');
  }

  Future<File> writeData(String data) async {
    final file = await _localFile;
    return file.writeAsString(data);
  }

  Future<String?> readData() async {
    try {
      final file = await _localFile;
      return await file.readAsString();
    } catch (e) {
      return null; // Cache miss
    }
  }
}

3. Implement SQLite Persistence

For large datasets requiring improved performance over simple files, implement an on-device database using sqflite.

import 'package:path/path.dart';
import 'package:sqflite/sqflite.dart';

class DatabaseService {
  late Database _database;

  Future<void> initDB() async {
    _database = await openDatabase(
      join(await getDatabasesPath(), 'app_cache.db'),
      onCreate: (db, version) {
        return db.execute(
          'CREATE TABLE cache_data(id INTEGER PRIMARY KEY, key TEXT, payload TEXT)',
        );
      },
      version: 1,
    );
  }

  Future<void> insertCache(String key, String payload) async {
    await _database.insert(
      'cache_data',
      {'key': key, 'payload': payload},
      conflictAlgorithm: ConflictAlgorithm.replace,
    );
  }

  Future<String?> getCache(String key) async {
    final List<Map<String, Object?>> maps = await _database.query(
      'cache_data',
      where: 'key = ?',
      whereArgs: [key], // MUST use whereArgs to prevent SQL injection
    );
    if (maps.isNotEmpty) {
      return maps.first['payload'] as String;
    }
    return null;
  }
}

4. Implement Offline-First Repository (Stream-based)

Combine local caching and remote fetching. Yield the cached data first (cache hit), then fetch from the network, update the cache, and yield the fresh data.

Stream<UserProfile> getUserProfile() async* {
  // 1. Check local cache
  final localData = await _databaseService.getCache('user_profile');
  if (localData != null) {
    yield UserProfile.fromJson(localData);
  }

  // 2. Fetch remote data
  try {
    final remoteData = await _apiClient.fetchUserProfile();
    // 3. Update cache
    await _databaseService.insertCache('user_profile', remoteData.toJson());
    // 4. Yield fresh data
    yield remoteData;
  } catch (e) {
    // Handle network failure; local data has already been yielded
  }
}

5. Implement FlutterEngine Caching (Android)

To minimize Flutter's initialization time when adding Flutter screens to an Android app, pre-warm and cache the FlutterEngine.

Pre-warm in Application class (Kotlin):

class MyApplication : Application() {
  lateinit var flutterEngine : FlutterEngine
  override fun onCreate() {
    super.onCreate()
    flutterEngine = FlutterEngine(this)
    // Optional: Configure initial route before executing entrypoint
    flutterEngine.navigationChannel.setInitialRoute("/cached_route");
    flutterEngine.dartExecutor.executeDartEntrypoint(
      DartExecutor.DartEntrypoint.createDefault()
    )
    FlutterEngineCache.getInstance().put("my_engine_id", flutterEngine)
  }
}

Consume in Activity/Fragment (Kotlin):

// For Activity
startActivity(
  FlutterActivity
    .withCachedEngine("my_engine_id")
    .backgroundMode(FlutterActivityLaunchConfigs.BackgroundMode.transparent)
    .build(this)
)

// For Fragment
val flutterFragment = FlutterFragment.withCachedEngine("my_engine_id")
    .renderMode(FlutterView.RenderMode.texture)
    .shouldAttachEngineToActivity(false)
    .build()

6. Optimize Image and Scroll Caching

Apply strict constraints to image caching and scrolling to prevent GPU memory bloat and layout passes.

ImageCache Validation: Verify cache hits without triggering loads using containsKey.

class CustomImageCache extends ImageCache {
  @override
  bool containsKey(Object key) {
    // Check if cache is tracking this key
    return super.containsKey(key);
  }
}

ScrollCacheExtent Implementation: Use the strongly-typed ScrollCacheExtent object for scrolling widgets (replaces deprecated cacheExtent and cacheExtentStyle).

ListView(
  // Use ScrollCacheExtent.pixels for pixel-based caching
  scrollCacheExtent: const ScrollCacheExtent.pixels(500.0),
  children: [ ... ],
)

Viewport(
  // Use ScrollCacheExtent.viewport for fraction-based caching
  scrollCacheExtent: const ScrollCacheExtent.viewport(0.5),
  slivers: [ ... ],
)

7. Validate-and-Fix Performance

Review the generated UI code for performance pitfalls.

  1. Check for saveLayer() triggers: Ensure Opacity, ShaderMask, ColorFilter, and Clip.antiAliasWithSaveLayer are only used when absolutely necessary. Replace Opacity with semitransparent colors or FadeInImage where possible.
  2. Check operator == overrides: Ensure operator == is NOT overridden on Widget objects unless they are leaf widgets whose properties rarely change.
  3. Check Intrinsic Passes: Ensure ListView and GridView use lazy builder methods (ListView.builder) and avoid intrinsic layout passes by setting fixed sizes where possible.

Constraints

  • SQL Injection Prevention: ALWAYS use whereArgs in sqflite queries. NEVER use string interpolation for SQL where clauses.
  • Engine Lifecycle: When using a cached FlutterEngine in Android, remember it outlives the Activity/Fragment. Explicitly call FlutterEngine.destroy() when it is no longer needed to clear resources.
  • Image Caching Limits: Raster cache entries are expensive to construct and use significant GPU memory. Only cache images when absolutely necessary. Do not artificially inflate ImageCache.maxByteSize.
  • Widget Equality: Do not override operator == on widgets to force caching, as this degrades performance to O(N²). Rely on const constructors instead.
  • Scroll Extents: NEVER use the deprecated cacheExtent (double) or cacheExtentStyle. ALWAYS use the ScrollCacheExtent object.
  • Web Workers: If targeting Flutter Web, remember that Dart isolates are not supported. Do not generate isolate-based background parsing for web targets.

适合场景

01

用户想查找某类 Agent Skill 时

02

需要根据任务场景推荐可安装能力包时

03

需要对比不同来源的安装命令和来源信息时

能力概览

能力 1

按任务关键词查找相关 Skills

能力 2

展示可复制的安装命令

能力 3

保留来源站点、仓库和原始说明,方便继续核验

能力 4

展示第三方安全扫描或审计结果

安装后应在对应宿主中按原始 README 的触发条件使用;具体调用方式请以来源页面和 README 为准。

平台分布

Codex

39.49%
按下载量换算3,128

Claude

27.72%
按下载量换算2,195

Cursor

19.19%
按下载量换算1,520

Gemini CLI

8.71%
按下载量换算690

安全审计

Gen Agent Trust Hub

通过

Socket

通过

Snyk

通过

权限和风险

需要联网

该 Skill 可能需要联网访问来源站点、仓库或外部 API;具体网络访问范围需要结合源码和 README 复核。

安装前确认

本站仅展示第三方公开信息,不托管安装包,不提供自动安装或运行环境。安装前应自行审查源码、依赖和命令行为。当前只有一个来源,正式发布前建议补源仓库或其他目录站核验。

来源信息

继续浏览同类 Skills