SkillAtlasSkill 详情

flutter-pre-caching

36 Flutter and Dart skills your coding agent loads by itself, sourced only from official documen...

审核状态:已审核Quality 72Security 78

复制安装命令

用 Codex 或 Claude 安装复制这段 Prompt,粘贴到 Codex、Claude 或其他助手里,让它先审查 Skill 页面再帮你安装。

复制前请先查看来源、License 和安全提示。

项目 README

来源文件:README.md

抓取于 2026年8月25日

Flutter AI Skills for Claude Code, Codex, Cursor, Antigravity, and Other AI Coding Agents

An agent prompt reading "Add Google sign-in to the profile screen" on the left; on the right, the firebase-auth and flutter-app-architecture skills are auto-selected from a list of dozens

36 Flutter and Dart skills your coding agent loads by itself, sourced only from official documentation.

A skill is a folder with a SKILL.md file. Your agent reads the description, decides a task matches, and pulls in the guidance — you don't paste anything into a rules file or remember to @-mention a doc. Install once, and Firebase Auth guidance shows up when you touch auth, Riverpod guidance when you touch providers.

A comprehensive, (almost) non-opinionated collection: everything here is derived from official Flutter, Dart, Firebase, and package documentation. No personal preferences, no invented conventions.

⚡ Quick start

npx skills add evanca/flutter-ai-rules

That's it. The Skills CLI discovers the packages under skills/ and installs them for supported agents.

Browse before installing, or take just one:

npx skills add evanca/flutter-ai-rules --list
npx skills add evanca/flutter-ai-rules --skill flutter-best-practices

Install as a plugin

This repo is also a plugin marketplace, so agents that support plugins can install the whole set and keep it updated in place. The manifests live at .claude-plugin/, .codex-plugin/, .cursor-plugin/, .agents/plugins/, and plugin.json — all pointing at the same skills/ directory.

Claude Code — plugin marketplaces:

/plugin marketplace add evanca/flutter-ai-rules
/plugin install flutter-ai-skills@flutter-ai-rules

Skills then load as flutter-ai-skills:bloc, flutter-ai-skills:riverpod, and so on.

Codex — plugins:

codex plugin marketplace add evanca/flutter-ai-rules
codex plugin install flutter-ai-skills@flutter-ai-rules

Cursor — plugins: in Cursor, run /add-plugin, or add the repo as a team marketplace under Dashboard → Settings → Plugins → Import from Repo:

https://github.com/evanca/flutter-ai-rules

Antigravity — plugins:

git clone --depth 1 https://github.com/evanca/flutter-ai-rules.git
agy plugin install ./flutter-ai-rules

Windsurf / Devin has no plugin manifest, but Cascade already scans .agents/skills/ and ~/.agents/skills/, so the manual copy below is the install path. GitHub Copilot doesn't read SKILL.md at all — see Rules and combined sets for what to use instead.

Prefer to do it by hand? Copy or symlink any skill folder into your agent's skills directory — .claude/skills/, .cursor/skills/, .codex/skills/, .agents/skills/ (Antigravity, Codex, Windsurf), .windsurf/skills/. Or vendor the whole set into your project:

git clone --depth 1 https://github.com/evanca/flutter-ai-rules.git temp_repo && mkdir -p .skills && cp -r temp_repo/skills/* .skills && rm -rf temp_repo

With a .skills/ folder you can also reference a skill explicitly when you want it: "Read @.skills/bloc/SKILL.md and create test coverage for the new methods."

🧠 What's in the box

Flutter and Dart foundations

SkillLoads when you're…
flutter-best-practicesWriting, reviewing, or planning Flutter code
effective-dartWriting Dart, naming things, adding doc comments
dart-3-updatesUsing records, patterns, sealed classes, switch expressions
flutter-app-architectureScaffolding a project or refactoring into layers
architecture-feature-firstDesigning folder structure for a new feature
flutter-errorsHitting RenderFlex overflows, unbounded constraints, layout errors
flutter-use-column-row-firstBuilding responsive layouts with Row, Column, Expanded, Flexible
flutter-pre-cachingPreloading fonts, images, animations, or config

State management

SkillLoads when you're…
blocCreating a Cubit or Bloc, modeling state, wiring providers
riverpodSetting up providers, combining requests, managing disposal
providerConsuming state, optimizing rebuilds, using ProxyProvider
flutter-change-notifierSetting up ChangeNotifier models and consuming them

Testing and review

SkillLoads when you're…
testingWriting unit, widget, or golden tests; fixing flaky tests
mockitoGenerating mocks, stubbing, verifying interactions
mocktailMocking without codegen, registering fallback values
patrol-e2e-testingWriting E2E tests that touch native permissions or dialogs
code-reviewReviewing a PR, branch, or diff

Firebase

SkillLoads when you're…
flutterfire-configureAdding Firebase to a project, running flutterfire configure
firebase-authSetting up auth, managing auth state, social sign-in
firebase-cloud-firestoreDesigning schemas, CRUD, listeners, pagination
firebase-databaseSyncing real-time data, structuring JSON trees
firebase-storageUploading and downloading files, managing metadata
firebase-analyticsLogging events, setting user properties
firebase-crashlyticsCapturing fatal and non-fatal errors
firebase-messagingSetting up FCM, handling background messages
firebase-in-app-messagingRunning in-app campaigns
firebase-remote-configImplementing feature flags or A/B tests
firebase-app-checkConfiguring attestation and debug tokens
firebase-cloud-functionsCalling callable functions, handling errors
firebase-aiGenerating text or chat with Gemini via firebase_ai
generate-images-with-firebase-aiGenerating or editing images with a Gemini image model (Nano Banana)
firebase-data-connectWriting GraphQL queries against Data Connect

Shipping and product

SkillLoads when you're…
accessibilityWorking on a11y, WCAG, screen readers, focus order
inclusive-designHandling i18n, global name/address forms, low-end devices
store-listing-assetsWriting store copy to character limits
revenuecat-testingTesting purchases, subscriptions, sandbox flows
developing-genkit-dartBuilding AI agents in Dart with Genkit

🗂️ Rules and combined sets (legacy)

Before skills existed, this repo shipped rule files you pasted into a config, plus pre-merged bundles squeezed under Windsurf's character cap. Both still work and both are still updated, but skills are the recommended path — they load contextually instead of consuming your context window on every request.

Reach for these only if your tool has no skills support, or you want one static file you fully control:

  • rules/ — six broad foundation files: effective_dart.md, flutter_app_architecture.md, flutter_errors.md, dart_3_updates.md, testing.md, code_review.md. Drop them in your project and reference them by name: "Read @rules/effective_dart.md and follow its conventions." Package-specific guidance (Bloc, Riverpod, Firebase, Mockito…) is skills-only now.
  • combined/ — seven topic bundles, each in a full and an __under_6K variant. Paste one into your global or local rules config and you're done. The trimmed variants stay under 6,000 characters to fit Windsurf's global_rules.md hard limit.

GitHub Copilot lives here rather than in the skills section, because it has no SKILL.md support. Three options, in the order Copilot documents them:

  • Copy a combined/ bundle to .github/copilot-instructions.md for repo-wide guidance.
  • Copy rules/ files into .github/instructions/ as <name>.instructions.md, each with applyTo: "**/*.dart" frontmatter, so they only load for Dart files.
  • Copilot also reads a root AGENTS.md, so a bundle pasted there works for Copilot, Codex, and Antigravity at once.

📏 Recommended file sizes by tool

Size guidance from each tool's own official documentation, for rule/instruction files and for SKILL.md files (accessed 2026-07-11).

ToolRule file — recommended sizeSKILL.md — recommended size
Claude CodeCLAUDE.md: under 200 lines (soft)Under 500 lines (soft); description 1,536 chars (hard)
Cursor.mdc rule: under 500 lines (soft)No numeric limit — "keep focused, move detail to separate files"
OpenAI CodexAGENTS.md: no limit statedSkill bundle: zip ≤ 50 MB, uncompressed file ≤ 25 MB, ≤ 500 files/version (no per-SKILL.md text limit)
Google Antigravityrule file: 12,000 chars each (hard)No numeric limit stated
Windsurfglobal_rules.md: 6,000 chars; .windsurf/rules/*.md: 12,000 chars/file (hard)No numeric limit — "keeps your context window lean"
GitHub Copilotcopilot-instructions.md: ≤ 2 pages (soft, approx.)Not supported — no repo-level SKILL.md

Notes:

  • Hard = enforced/truncated at the limit; soft = a documented quality recommendation.
  • Only Claude Code publishes a numeric SKILL.md length recommendation (under 500 lines). Cursor, Windsurf, and Antigravity just say "keep it focused/lean" with no figure; OpenAI documents skill-bundle limits (50 MB zip / 25 MB per file / 500 files) rather than a text length; and GitHub Copilot has no repo-level SKILL.md — it uses copilot-instructions.md plus path-specific *.instructions.md (no size limit stated for the latter).
  • Claude Code loads CLAUDE.md in full regardless of length, but notes files over 200 lines "consume more context and reduce adherence"; its auto-memory MEMORY.md loads only the "first 200 lines or 25KB, whichever comes first."
  • Windsurf is still named Windsurf; its docs are served through Cognition (docs.windsurf.com → docs.devin.ai) and reference .windsurf/rules and .windsurf/skills.
  • This repo keeps the combined/ sets under 6,000 characters to satisfy the strictest hard limit above (Windsurf global_rules.md).

Official sources: Claude Code — memory · skills | Cursor — rules · skills | OpenAI Codex — AGENTS.md · skills | Google Antigravity — rules · skills | Windsurf — rules & skills | GitHub Copilot — instructions

📌 No opinions, just documentation

Every skill is sourced from official documentation — no personal preferences or subjective interpretations. That's intentional. You're free to alter them to taste, but this repo stays objective by sticking to the source.

One consequence worth knowing: skills can contradict each other, because their sources do. If one package recommends a folder layout and another recommends a different one, you'll see both.

Content is re-fetched from upstream docs on a schedule, so skills track the official guidance as it changes rather than freezing at whatever was true when they were written.

🛠️ Contributing

Contributions are welcome:

  1. Fork this repository.
  2. Add or modify a skill in skills/, or a rule in rules/.
  3. Open a pull request explaining the change.

Include an official documentation link for anything you add or change. That's the one hard requirement — it's what keeps the repo objective and reviewable. If your source isn't already listed in ATTRIBUTION.md, add it there with its license — and if that license isn't a permissive one, restate the guidance instead of quoting it.

📚 Sources

Official documentation these skills are built from:

Flutter — App Architecture · Common Errors · Simple State Management

Dart — Effective Dart · Language tour · Records · Patterns · Pattern types · Branches

State management — Bloc · Riverpod · Provider

Testing — Mockito · Mocktail · Patrol

Firebase — Firebase for Flutter · FlutterFire · Multiple flavors with the FlutterFire CLI

📄 License

MIT — for this repository's own content: the choice of topics, the trigger descriptions, and the wording and structure of every skill.

The underlying documentation keeps its own terms. Most of it is CC BY 4.0 (Flutter, Dart, Firebase), with code samples under BSD-3 or Apache 2.0, package READMEs under MIT or Apache 2.0, and a few sources — Apple, Google Play, RevenueCat — that aren't openly licensed and are therefore restated as fact rather than copied. ATTRIBUTION.md maps every source to its license and to the skills built on it.

If you redistribute this repo or lift a single skill out of it, keep the source links — that's what the CC BY attribution requirement actually asks for.

数据与 AI

中风险

  • 来源需自行核对维护者身份。
  • 未检测到明显脚本安装指令。
  • 可能需要外部 token、网络权限或第三方服务。
  • 未检测到高风险命令。
  • 扫描发现:2 条。

Codex — Git Clone 安装

  1. 安装前请先查看来源仓库和风险报告。
  2. 克隆仓库:git clone https://github.com/evanca/flutter-ai-rules.git
  3. 将 "skills/flutter-pre-caching" 文件夹复制到 Codex 的 skills 目录中。
  4. 重启 Codex 让新的 skill 生效。

Codex — 手动复制安装

  1. 安装前请先查看来源仓库和风险报告。
  2. 从源仓库下载 SKILL.md 及相关文件。
  3. 在 Codex 的 skills 目录中创建新文件夹。
  4. 将所有 skill 文件复制到新文件夹中。
  5. 重启 Codex 让新的 skill 生效。

Claude Code — Git Clone 安装

  1. 安装前请先查看来源仓库和风险报告。
  2. 克隆仓库:git clone https://github.com/evanca/flutter-ai-rules.git
  3. 将 "skills/flutter-pre-caching" 文件夹复制到 Claude Code 的 skills 目录中。
  4. 重启 Claude Code 让新的 skill 生效。

Claude Code — 手动复制安装

  1. 安装前请先查看来源仓库和风险报告。
  2. 从源仓库下载 SKILL.md 及相关文件。
  3. 在 Claude Code 的 skills 目录中创建新文件夹。
  4. 将所有 skill 文件复制到新文件夹中。
  5. 重启 Claude Code 让新的 skill 生效。

Cursor — Git Clone 安装

  1. 安装前请先查看来源仓库和风险报告。
  2. 克隆仓库:git clone https://github.com/evanca/flutter-ai-rules.git
  3. 将 "skills/flutter-pre-caching" 文件夹复制到 Cursor 的 skills 目录中。
  4. 重启 Cursor 让新的 skill 生效。

Cursor — 手动复制安装

  1. 安装前请先查看来源仓库和风险报告。
  2. 从源仓库下载 SKILL.md 及相关文件。
  3. 在 Cursor 的 skills 目录中创建新文件夹。
  4. 将所有 skill 文件复制到新文件夹中。
  5. 重启 Cursor 让新的 skill 生效。

GitHub Copilot — Git Clone 安装

  1. 安装前请先查看来源仓库和风险报告。
  2. 克隆仓库:git clone https://github.com/evanca/flutter-ai-rules.git
  3. 将 "skills/flutter-pre-caching" 文件夹复制到 GitHub Copilot 的 skills 目录中。
  4. 重启 GitHub Copilot 让新的 skill 生效。

GitHub Copilot — 手动复制安装

  1. 安装前请先查看来源仓库和风险报告。
  2. 从源仓库下载 SKILL.md 及相关文件。
  3. 在 GitHub Copilot 的 skills 目录中创建新文件夹。
  4. 将所有 skill 文件复制到新文件夹中。
  5. 重启 GitHub Copilot 让新的 skill 生效。

Windsurf — Git Clone 安装

  1. 安装前请先查看来源仓库和风险报告。
  2. 克隆仓库:git clone https://github.com/evanca/flutter-ai-rules.git
  3. 将 "skills/flutter-pre-caching" 文件夹复制到 Windsurf 的 skills 目录中。
  4. 重启 Windsurf 让新的 skill 生效。

Windsurf — 手动复制安装

  1. 安装前请先查看来源仓库和风险报告。
  2. 从源仓库下载 SKILL.md 及相关文件。
  3. 在 Windsurf 的 skills 目录中创建新文件夹。
  4. 将所有 skill 文件复制到新文件夹中。
  5. 重启 Windsurf 让新的 skill 生效。
查看 SKILL.md 原文
name: flutter-pre-caching
description: "Use when preloading fonts, asset/network images, Lottie/Rive animations, local JSON/config, warming initial API data, or optimizing Flutter Web startup."
license: MIT

Pre-caching in Flutter and Flutter Web

Pre-caching helps avoid jank, loading flashes, font swaps, and delayed first renders.

The key rule:

Pre-cache only what the user will likely see in the next 1 to 2 screens.

Do not pre-cache the whole app. That can slow startup and waste memory.


1. Google Fonts

Runtime Google Fonts preloading

Use GoogleFonts.pendingFonts() to load the font variants before showing text.

import 'package:flutter/material.dart';
import 'package:google_fonts/google_fonts.dart';

class ExampleSimple extends StatefulWidget {
  const ExampleSimple({super.key});

  @override
  State<ExampleSimple> createState() => _ExampleSimpleState();
}

class _ExampleSimpleState extends State<ExampleSimple> {
  late final Future<List<void>> googleFontsPending;

  @override
  void initState() {
    super.initState();

    googleFontsPending = GoogleFonts.pendingFonts([
      GoogleFonts.poppins(),
      GoogleFonts.montserrat(fontStyle: FontStyle.italic),
    ]);
  }

  @override
  Widget build(BuildContext context) {
    final pushButtonTextStyle = GoogleFonts.poppins(
      textStyle: Theme.of(context).textTheme.headlineMedium,
    );

    final counterTextStyle = GoogleFonts.montserrat(
      fontStyle: FontStyle.italic,
      textStyle: Theme.of(context).textTheme.displayLarge,
    );

    return FutureBuilder<List<void>>(
      future: googleFontsPending,
      builder: (context, snapshot) {
        if (snapshot.connectionState != ConnectionState.done) {
          return const SizedBox();
        }

        return Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            Text(
              'You have pushed the button this many times:',
              style: pushButtonTextStyle,
            ),
            Text(
              '0',
              style: counterTextStyle,
            ),
          ],
        );
      },
    );
  }
}

Production recommendation

For production and offline support, prefer bundling critical fonts as assets.

flutter:
  fonts:
    - family: AppFont
      fonts:
        - asset: assets/fonts/AppFont-Regular.ttf
        - asset: assets/fonts/AppFont-Bold.ttf
          weight: 700

Use it in the app theme:

MaterialApp(
  theme: ThemeData(
    fontFamily: 'AppFont',
  ),
)

2. Asset images

Use precacheImage for images that appear soon.

@override
void didChangeDependencies() {
  super.didChangeDependencies();

  precacheImage(
    const AssetImage('assets/images/header.png'),
    context,
  );
}

Then use the image normally:

Image.asset('assets/images/header.png')

3. Network images

Use precacheImage with NetworkImage.

@override
void didChangeDependencies() {
  super.didChangeDependencies();

  precacheImage(
    const NetworkImage('https://example.com/image.png'),
    context,
  );
}

Then use it normally:

Image.network('https://example.com/image.png')

Important: precacheImage warms Flutter’s in-memory image cache. It does not provide long-term offline caching.

For disk caching, use a package like cached_network_image:

dependencies:
  cached_network_image: ^latest

Example:

CachedNetworkImage(
  imageUrl: 'https://example.com/image.png',
)

4. Multiple image preloading

@override
void didChangeDependencies() {
  super.didChangeDependencies();

  final images = <ImageProvider>[
    const AssetImage('assets/images/header.png'),
    const AssetImage('assets/images/avatar.png'),
    const NetworkImage('https://example.com/banner.png'),
  ];

  for (final image in images) {
    precacheImage(image, context);
  }
}

5. Waiting until images are ready

precacheImage returns a Future<void>, so you can wait before rendering the real UI.

late Future<void> _preloadImagesFuture;

@override
void didChangeDependencies() {
  super.didChangeDependencies();

  _preloadImagesFuture = Future.wait([
    precacheImage(
      const AssetImage('assets/images/header.png'),
      context,
    ),
    precacheImage(
      const NetworkImage('https://example.com/banner.png'),
      context,
    ),
  ]);
}

@override
Widget build(BuildContext context) {
  return FutureBuilder<void>(
    future: _preloadImagesFuture,
    builder: (context, snapshot) {
      if (snapshot.connectionState != ConnectionState.done) {
        return const CircularProgressIndicator();
      }

      return Column(
        children: [
          Image.asset('assets/images/header.png'),
          Image.network('https://example.com/banner.png'),
        ],
      );
    },
  );
}

[!NOTE] Use didChangeDependencies, not initState, when you need context for precacheImage.


6. What should normally be pre-cached on app start?

Good candidates:

  • App logo
  • First screen hero image
  • First visible background image
  • Current user avatar
  • First visible card/list images
  • Main font variants
  • Small local config files
  • Translations needed for first paint
  • First API request
  • Lottie/Rive animation shown immediately

Bad candidates:

  • All product images
  • All gallery images
  • All remote feed images
  • All icons in the app
  • All route images
  • Every image from every screen
  • Large animations not shown immediately

7. Practical app-start preloader

class AppPreloader {
  const AppPreloader();

  Future<void> preload(BuildContext context) async {
    await Future.wait([
      _precacheImages(context),
      _loadCriticalAssets(),
      _warmUpInitialData(),
    ]);
  }

  Future<void> _precacheImages(BuildContext context) {
    return Future.wait([
      precacheImage(
        const AssetImage('assets/images/home_hero.png'),
        context,
      ),
      precacheImage(
        const AssetImage('assets/images/logo.png'),
        context,
      ),
    ]);
  }

  Future<void> _loadCriticalAssets() async {
    await rootBundle.loadString('assets/config/app_config.json');
  }

  Future<void> _warmUpInitialData() async {
    // Example:
    // await userRepository.getCurrentUser();
  }
}

Usage:

late Future<void> _preloadFuture;

@override
void didChangeDependencies() {
  super.didChangeDependencies();

  _preloadFuture = const AppPreloader().preload(context);
}

With FutureBuilder:

@override
Widget build(BuildContext context) {
  return FutureBuilder<void>(
    future: _preloadFuture,
    builder: (context, snapshot) {
      if (snapshot.connectionState != ConnectionState.done) {
        return const SplashScreen();
      }

      return const HomeScreen();
    },
  );
}

8. Local JSON / config preloading

Useful for feature flags, local app config, mock data, translations, or onboarding content.

import 'package:flutter/services.dart';

final configJson = await rootBundle.loadString(
  'assets/config/app_config.json',
);

Example:

class AppConfigLoader {
  Future<String> load() {
    return rootBundle.loadString('assets/config/app_config.json');
  }
}

9. Initial API request warm-up

This is not pre-caching in the Flutter image-cache sense, but it is often the most useful startup optimization.

final userFuture = userRepository.getCurrentUser();
final dashboardFuture = dashboardRepository.getDashboard();

Example:

class StartupData {
  const StartupData({
    required this.user,
    required this.dashboard,
  });

  final User user;
  final Dashboard dashboard;
}

Future<StartupData> loadStartupData() async {
  final results = await Future.wait([
    userRepository.getCurrentUser(),
    dashboardRepository.getDashboard(),
  ]);

  return StartupData(
    user: results[0] as User,
    dashboard: results[1] as Dashboard,
  );
}

10. Lottie preloading

If the animation appears immediately, preload it.

final composition = await AssetLottie(
  'assets/animations/success.json',
).load();

Use this only for animations shown early. Avoid preloading many large animations on app start.


11. Rive preloading

Rather than triggering the asset load during a build (which causes jank), preload the RiveFile byte data in advance:

import 'package:flutter/services.dart';
import 'package:rive/rive.dart';

// Preload the RiveFile
final data = await rootBundle.load('assets/animations/character.riv');
final riveFile = RiveFile.import(data);

// Display using direct constructor to avoid initialization delays:
RiveAnimation.direct(riveFile);

This ensures that the animation renders immediately upon widget mount.


12. Shader warm-up

Most apps do not need this. It can help if you have:

  • Heavy custom painting
  • Complex transitions
  • Known animation jank
  • Older rendering paths

Basic shape:

class CustomShaderWarmUp extends ShaderWarmUp {
  @override
  void warmUpOnCanvas(Canvas canvas) {
    final paint = Paint();

    canvas.drawRect(
      const Rect.fromLTWH(0, 0, 100, 100),
      paint,
    );
  }
}

Then set it before runApp:

void main() {
  PaintingBinding.instance.shaderWarmUp = CustomShaderWarmUp();

  runApp(const MyApp());
}

Use this only when profiling shows shader compilation jank.


13. Flutter Web: different mindset

On Flutter Web, think less:

  • Pre-cache everything in memory

Think more:

  • Make the browser download key files early
  • Warm Flutter cache only for first-screen assets
  • Avoid surprise font fallback downloads
  • Avoid loading huge assets before first paint

14. Flutter Web image preload

For critical first-screen images, use both browser preload and Flutter precacheImage.

In web/index.html:

<link
  rel="preload"
  href="assets/assets/images/home_hero.png"
  as="image"
>

In Flutter:

await precacheImage(
  const AssetImage('assets/images/home_hero.png'),
  context,
);

Why both?

  • HTML preload starts the browser download earlier.
  • precacheImage warms Flutter's image cache.

15. Flutter Web network image preload

In web/index.html:

<link
  rel="preload"
  href="https://example.com/banner.png"
  as="image"
>

In Flutter:

await precacheImage(
  const NetworkImage('https://example.com/banner.png'),
  context,
);

Only do this for images the user is almost guaranteed to see.


16. Flutter Web font preload

Declare the font in pubspec.yaml:

flutter:
  fonts:
    - family: AppFont
      fonts:
        - asset: assets/fonts/AppFont-Regular.ttf
        - asset: assets/fonts/AppFont-Bold.ttf
          weight: 700

Preload the critical font in web/index.html:

<link
  rel="preload"
  href="assets/assets/fonts/AppFont-Regular.ttf"
  as="font"
  type="font/ttf"
  crossorigin
>

Use it in Flutter:

ThemeData(
  fontFamily: 'AppFont',
)

Usually preload:

  • Regular
  • Bold
  • Maybe medium

Avoid preloading every weight and italic variant unless the first screen needs them.


17. Flutter Web and emojis

Emojis can trigger font fallback work.

Example:

Text('Welcome 👋 🎉')

On web, this can cause:

  • Extra font download
  • Delayed render
  • Fallback font swap
  • Blank boxes
  • Different emoji style across platforms

18. Option 1: avoid emojis on first paint

Simple and effective:

Text('Welcome')

Then show emojis after the app has loaded:

Text('Welcome 👋')

This is often the best option if emojis are decorative.


19. Option 2: bundle and preload an emoji font

Add the font to pubspec.yaml:

flutter:
  fonts:
    - family: NotoColorEmoji
      fonts:
        - asset: assets/fonts/NotoColorEmoji.ttf

Preload it in web/index.html:

<link
  rel="preload"
  href="assets/assets/fonts/NotoColorEmoji.ttf"
  as="font"
  type="font/ttf"
  crossorigin
>

Use it where needed:

const Text(
  '👋 🎉 ❤️',
  style: TextStyle(
    fontFamily: 'NotoColorEmoji',
  ),
)

Important:

  • Emoji fonts can be large.
  • Do not bundle a huge emoji font unless emojis are important to your product.

20. When emoji preloading makes sense

Good cases:

  • Chat app
  • Reactions
  • Comments
  • Social UI
  • Emoji picker
  • Emoji-heavy onboarding
  • Brand uses emoji heavily

Bad cases:

  • One decorative emoji on the welcome screen
  • Random emoji in a button
  • Rare emoji usage deep in the app

Rule:

  • If emojis are decorative, delay them or remove them from first paint.
  • If emojis are core to the product, use a known emoji rendering strategy.

21. Flutter Web renderer files

Flutter Web startup can also include renderer assets, for example CanvasKit or Skwasm files.

Usually, you do not preload these from Dart. You configure the renderer through Flutter Web initialization.

Example in web bootstrap:

_flutter.loader.load({
  config: {
    renderer: 'canvaskit',
  },
});

Other configs can include things like:

_flutter.loader.load({
  config: {
    renderer: 'canvaskit',
    canvasKitBaseUrl: '/canvaskit/',
  },
});

Most apps should let Flutter manage this unless there is a clear hosting or performance reason to change it.


22. Practical Flutter Web startup list

Usually preload:

  • App font regular/bold
  • Logo
  • First hero image
  • First visible background image
  • Critical above-the-fold asset images
  • Emoji font only if emojis are core to first paint
  • Small config needed immediately

Usually avoid:

  • All emoji fonts
  • All product images
  • All route images
  • All remote avatars
  • Large Lottie/Rive files not shown immediately
  • Every font weight
  • Every image in assets

23. Suggested folder structure

assets/
  images/
    logo.png
    home_hero.png
    onboarding_hero.png

  fonts/
    AppFont-Regular.ttf
    AppFont-Bold.ttf
    NotoColorEmoji.ttf

  config/
    app_config.json

  animations/
    success.json
    character.riv

24. Example pubspec.yaml

flutter:
  assets:
    - assets/images/
    - assets/config/
    - assets/animations/

  fonts:
    - family: AppFont
      fonts:
        - asset: assets/fonts/AppFont-Regular.ttf
        - asset: assets/fonts/AppFont-Bold.ttf
          weight: 700

    - family: NotoColorEmoji
      fonts:
        - asset: assets/fonts/NotoColorEmoji.ttf

25. Example web/index.html preload block

<!-- App fonts -->
<link
  rel="preload"
  href="assets/assets/fonts/AppFont-Regular.ttf"
  as="font"
  type="font/ttf"
  crossorigin
>

<link
  rel="preload"
  href="assets/assets/fonts/AppFont-Bold.ttf"
  as="font"
  type="font/ttf"
  crossorigin
>

<!-- Only if emojis are critical to first paint -->
<link
  rel="preload"
  href="assets/assets/fonts/NotoColorEmoji.ttf"
  as="font"
  type="font/ttf"
  crossorigin
>

<!-- Critical images -->
<link
  rel="preload"
  href="assets/assets/images/logo.png"
  as="image"
>

<link
  rel="preload"
  href="assets/assets/images/home_hero.png"
  as="image"
>

[!NOTE] Flutter web asset URLs often include assets/assets/... because Flutter serves declared assets under the assets/ path, while your asset path also starts with assets/.

For example:

  • Flutter asset: assets/images/logo.png
  • Web URL: assets/assets/images/logo.png

26. Complete startup example

import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:google_fonts/google_fonts.dart';

class AppStartupPreloader {
  const AppStartupPreloader();

  Future<void> preload(BuildContext context) async {
    await Future.wait([
      _preloadFonts(),
      _preloadImages(context),
      _preloadLocalConfig(),
      _preloadStartupData(),
    ]);
  }

  Future<void> _preloadFonts() {
    return GoogleFonts.pendingFonts([
      GoogleFonts.inter(),
      GoogleFonts.inter(fontWeight: FontWeight.w700),
    ]);
  }

  Future<void> _preloadImages(BuildContext context) {
    return Future.wait([
      precacheImage(
        const AssetImage('assets/images/logo.png'),
        context,
      ),
      precacheImage(
        const AssetImage('assets/images/home_hero.png'),
        context,
      ),
    ]);
  }

  Future<void> _preloadLocalConfig() async {
    await rootBundle.loadString('assets/config/app_config.json');
  }

  Future<void> _preloadStartupData() async {
    // Start your critical first API calls here.
    //
    // Example:
    // await userRepository.getCurrentUser();
    // await dashboardRepository.getDashboard();
  }
}

Usage:

class StartupGate extends StatefulWidget {
  const StartupGate({super.key});

  @override
  State<StartupGate> createState() => _StartupGateState();
}

class _StartupGateState extends State<StartupGate> {
  Future<void>? _startupFuture;

  @override
  void didChangeDependencies() {
    super.didChangeDependencies();

    _startupFuture ??= const AppStartupPreloader().preload(context);
  }

  @override
  Widget build(BuildContext context) {
    return FutureBuilder<void>(
      future: _startupFuture,
      builder: (context, snapshot) {
        if (snapshot.connectionState != ConnectionState.done) {
          return const SplashScreen();
        }

        return const HomeScreen();
      },
    );
  }
}

27. Final rule of thumb

Pre-cache this:

  • What the user sees immediately.
  • What the user will almost certainly see next.
  • What would cause visible jank if it loads late.

Do not pre-cache this:

  • Everything.
  • Large files that may never be used.
  • Remote images far below the fold.
  • Decorative emoji/font assets that are not critical.

For Flutter Web specifically:

  • Use HTML preload for critical browser downloads.
  • Use Flutter precacheImage for Flutter image cache.
  • Bundle critical fonts.
  • Avoid emoji font fallback on first paint.
  • Delay decorative emojis.

References

发现问题?提交给管理员复核

评分:

评论 (0)

暂无评论,成为第一个评论者吧!