diff --git a/eleventy.config.ts b/eleventy.config.ts
index f86c37ef5fc..54957a82749 100644
--- a/eleventy.config.ts
+++ b/eleventy.config.ts
@@ -76,6 +76,7 @@ export default function (eleventyConfig: UserConfig) {
eleventyConfig.addPassthroughCopy('src/content/assets/js');
eleventyConfig.addPassthroughCopy('src/content/llms.txt');
eleventyConfig.addPassthroughCopy({ 'site-shared/pkgs/inject_dartpad/lib/inject_dartpad.js': 'assets/js/inject_dartpad.js' });
+ eleventyConfig.addPassthroughCopy('src/content/assets/files', { expand: true });
eleventyConfig.addPassthroughCopy('src/content/assets/images', { expand: true });
eleventyConfig.addPassthroughCopy('src/content/cookbook/img-files', { expand: true });
eleventyConfig.addPassthroughCopy('src/content/f', {
@@ -85,6 +86,7 @@ export default function (eleventyConfig: UserConfig) {
eleventyConfig.addPassthroughCopy('src/content/tools/devtools/release-notes', {
filter: (path: string) => path.includes('src') || path.includes('images'),
});
+ eleventyConfig.ignores.add("src/content/assets/files/**/*.md");
if (shouldOptimize) {
// If building for production, minify/optimize the HTML output.
diff --git a/src/_data/sidenav.yml b/src/_data/sidenav.yml
index a577e07b8d3..c9fd1ea9721 100644
--- a/src/_data/sidenav.yml
+++ b/src/_data/sidenav.yml
@@ -208,11 +208,13 @@
- title: Build a news app
permalink: /resources/news-toolkit
-- title: Create with AI
+- title: AI solutions
permalink: /ai
children:
- - title: Overview
+ - title: Create with AI
permalink: /ai/create-with-ai
+ - title: AI Rules
+ permalink: /ai/ai-rules
- title: AI Toolkit
permalink: /ai-toolkit
expanded: false
diff --git a/src/content/ai/ai-rules.md b/src/content/ai/ai-rules.md
new file mode 100644
index 00000000000..2138e6beb55
--- /dev/null
+++ b/src/content/ai/ai-rules.md
@@ -0,0 +1,83 @@
+---
+title: AI rules for Flutter and Dart
+description: >
+ Learn how to add AI rules to tools that accelerate your
+ development workflow.
+---
+
+This guide covers how you can leverage AI rules to
+streamline your Flutter and Dart development.
+
+## Overview
+
+AI-powered editors use rules files to provide context and
+instructions to an underlying LLM. These files help you:
+
+* Customize AI behavior to your team's needs.
+* Enforce project best practices for code style and
+ design.
+* Provide critical project context to the AI.
+
+
+ download
+ Download the Flutter and Dart rules template
+
+
+## Environments that support rules
+
+Many AI environments support rules files to guide
+LLM behavior. Here are some common examples and their
+corresponding rule file names:
+
+| Environment | Rules File | Installation Instructions |
+| :--- | :--- | :--- |
+| Copilot powered IDEs | `copilot-instructions.md` | [Configure .github/copilot-instructions.md][] |
+| Cursor | `cursor.md` | [Configure cursorrules.md][] |
+| Firebase Studio | `airules.md` | [Configure airules.md][] |
+| Gemini CLI | `GEMINI.md` | [Configure gemini.md][] |
+| JetBrains IDEs | `guidelines.md` | [Configure guidelines.md][] |
+| VS Code | `.instructions.md` | [Configure .instructions.md][] |
+| Windsurf | `guidelines.md` | [Configure guidelines.md][] |
+
+[Configure airules.md]: https://firebase.google.com/docs/studio/set-up-gemini#custom-instructions
+[Configure .github/copilot-instructions.md]: https://code.visualstudio.com/docs/copilot/copilot-customization#_custom-instructions
+[Configure cursorrules.md]: https://docs.cursor.com/en/context/rules
+[Configure guidelines.md]: https://www.jetbrains.com/help/junie/customize-guidelines.html
+[Configure .instructions.md]: https://code.visualstudio.com/docs/copilot/copilot-customization#_custom-instructions
+[Configure guidelines.md]: https://docs.windsurf.com/windsurf/cascade/memories#rules
+[Configure GEMINI.md]: https://codelabs.developers.google.com/gemini-cli-hands-on
+
+## Create rules for your editor
+
+You can adapt our Flutter and Dart rules template for your
+specific environment. To do so, follow these steps:
+
+1. Download the Flutter and Dart rules template:
+ flutter-rules-template.md
+
+1. In an LLM like [Gemini][], attach the
+ `flutter-rules-template.md` file that you downloaded in
+ the last step.
+
+1. Provide a prompt to reformat the file for your desired
+ editor.
+
+ Example prompt:
+
+ ```text
+ Convert the attached flutter-rules-template.txt file
+ into a guidelines.md file for JetBrains IDE. Make sure
+ to use the styles required for a guidelines.md file.
+ ```
+
+1. Review the LLM's output and make any necessary
+ adjustments.
+
+1. Follow your environment's instructions to add the new
+ rules file. This may involve adding to an existing file
+ or creating a new one.
+
+1. Verify that your AI assistant is using the new rules to
+ guide its responses.
+
+[Gemini]: https://gemini.google.com/
diff --git a/src/content/ai/create-with-ai.md b/src/content/ai/create-with-ai.md
index 42acaaa9aea..e4e4a240ca1 100644
--- a/src/content/ai/create-with-ai.md
+++ b/src/content/ai/create-with-ai.md
@@ -9,6 +9,21 @@ description: >
This guide covers how you can leverage AI tools to build AI-powered features for
your Flutter apps and streamline your Flutter and Dart development.
+## Overview
+
+AI can be used for building AI-powered apps with Flutter and
+for accelerating your development workflow. You can
+integrate AI-powered features like
+natural language understanding and content generation
+directly into your Flutter app using powerful SDKs,
+like the Firebase SDK for Generative AI. You can also use
+AI tools, such as Gemini Code Assist and Gemini CLI, to help
+with code generation and scaffolding. These tools are
+powered by the Dart and Flutter MCP Server, which provides
+AI with a rich context about your codebase. Additionally,
+rules files help fine-tune the AI's behavior and enforce
+project-specific best practices.
+
## Build AI-powered experiences with Flutter
Using AI in your Flutter app unlocks new user experiences that allow your app
@@ -24,7 +39,9 @@ resources:
* [Flutter AI Toolkit][] - A sample app with pre-built widgets to help you build
AI-powered features in Flutter
----
+[Firebase AI Logic]: {{site.firebase}}/docs/ai-logic
+[firebase-ai-logic-docs]: {{site.firebase}}/docs/ai-logic/get-started
+[Flutter AI Toolkit]: {{site.url}}/ai-toolkit
## AI development tools
@@ -34,9 +51,9 @@ you write code faster, understand complex concepts, and reduce boilerplate.
### Gemini Code Assist
-[Gemini Code Assist][] is an AI-powered collaborator available in Visual Studio Code
-and JetBrains IDEs (including Android Studio). It has a deep understanding of
-your project's codebase and can help you with:
+[Gemini Code Assist][] is an AI-powered collaborator available in
+Visual Studio Code and JetBrains IDEs (including Android Studio). It has a deep
+understanding of your project's codebase and can help you with:
* **Code completion and generation**: It suggests and generates entire blocks of
code based on the context of what you're writing.
@@ -46,6 +63,7 @@ your project's codebase and can help you with:
Code Assist to explain it and suggest a fix, and
[Dart and Flutter MCP Server][dart-mcp-flutter-docs]
+[Gemini Code Assist]: https://codeassist.google/
### Gemini CLI
@@ -60,15 +78,16 @@ environment. You can use it to:
To get started, visit the [Gemini CLI][] website, or try this
[Gemini CLI codelab][].
----
+[Gemini CLI]: {{site.github}}/google-gemini/gemini-cli
+[Gemini CLI codelab]: https://codelabs.developers.google.com/gemini-cli-hands-on
## Dart and Flutter MCP Server
To provide assistance during Flutter development, AI tools such as
Gemini Code Assist and Gemini CLI need to communicate with Dart
and Flutter's developer tools. The Dart and
-Flutter MCP (model context protocol) Server facilitates this
-communication. The model context protocol is a specification that
+Flutter MCP Server facilitates this communication.
+MCP (model context protocol) is a specification that
outlines how development tools can share the context of a user's code
with an AI model, which allows the AI to better understand and interact
with the code.
@@ -78,18 +97,18 @@ and fix errors, hot reload, get the selected widget, and more. This bridges
the gap between the AI's natural language understanding, and
Dart and Flutter's suite of developer tools.
-To get started, check out the official documentation for the [Dart and Flutter MCP server][dart-mcp-dart-docs]
+To get started, check out the official documentation for the
+[Dart and Flutter MCP server][dart-mcp-dart-docs]
on dart.dev and the [Dart and Flutter MCP repository][dart-mcp-github].
----
-
-[Gemini Code Assist]: https://codeassist.google/
-[Gemini CLI]: {{site.github}}/google-gemini/gemini-cli
-[Gemini CLI codelab]: https://codelabs.developers.google.com/gemini-cli-hands-on
-[Firebase AI Logic]: {{site.firebase}}/docs/ai-logic
-[firebase-ai-logic-docs]: {{site.firebase}}/docs/ai-logic/get-started
-[How to build agentic apps with Flutter and Firebase AI Logic]: {{site.yt.watch}}/watch?v=xo271p-Fl_4
-[Flutter AI Toolkit]: {{site.url}}/ai-toolkit
[dart-mcp-dart-docs]: {{site.dart-site}}/tools/mcp-server
[dart-mcp-github]: {{site.github}}/dart-lang/ai/tree/main/pkgs/dart_mcp_server
[dart-mcp-flutter-docs]: #dart-and-flutter-mcp-server
+
+## Rules for Flutter and Dart
+
+You can use a rules file with AI-powered editors to provide
+context and instructions to an underlying LLM. To get
+started, see the [AI rules for Flutter and Dart][] guide.
+
+[AI rules for Flutter and Dart]: /ai/ai-rules
diff --git a/src/content/assets/files/flutter-rules-template.md b/src/content/assets/files/flutter-rules-template.md
new file mode 100644
index 00000000000..507488f66bd
--- /dev/null
+++ b/src/content/assets/files/flutter-rules-template.md
@@ -0,0 +1,308 @@
+# AI rules for Flutter
+
+You are an expert in Flutter and Dart development. Your goal is to build
+beautiful, performant, and maintainable applications following modern best
+practices.
+
+## Project Structure
+* Assumes a standard Flutter project structure with `lib/main.dart` as the
+ primary application entry point.
+
+## Package Management
+* If a new feature requires an external package, the AI will identify the most
+ suitable and stable package from pub.dev.
+* To add a regular dependency, it will execute `flutter pub add
+ `.
+* To add a development dependency, it will execute `flutter pub add
+ dev:`.
+
+## Code Quality
+* Adhere to maintainable code structure and separation of concerns (e.g., UI
+ logic separate from business logic).
+* Adhere to meaningful and consistent naming conventions.
+
+## Dart Best Practices
+* Follow the official Effective Dart guidelines.
+* Define related classes within the same library file. For large libraries,
+ export smaller, private libraries from a single top-level library.
+* Group related libraries in the same folder.
+* Add documentation comments to all public APIs, including classes,
+ constructors, methods, and top-level functions.
+* Write clear comments for complex or non-obvious code. Avoid over-commenting.
+* Don't add trailing comments.
+* Ensure proper use of `async`/`await` for asynchronous operations with robust
+ error handling.
+* Use pattern matching features where they simplify the code.
+
+## Flutter Best Practices
+* Widgets (especially `StatelessWidget`) are immutable; when the UI needs to
+ change, Flutter rebuilds the widget tree.
+* Prefer composing smaller widgets over extending existing ones.
+* Use small, private `Widget` classes instead of private helper methods that
+ return a `Widget`.
+* Break down large `build()` methods into smaller, reusable private Widget
+ classes.
+* Use `ListView.builder` to create lazy-loaded lists for performance.
+* Use `const` constructors for widgets and in `build()` methods whenever
+ possible to optimize performance.
+* Avoid performing expensive operations, like network calls or complex
+ computations, directly within `build()` methods.
+
+## Application Architecture
+* Aim for separation of concerns similar to MVC/MVVM, with defined Model,
+ View, and ViewModel/Controller roles.
+
+### State Management
+* Default to Flutter's built-in state management solutions. Do not use a
+ third-party package unless explicitly requested.
+* Use `Streams` and `StreamBuilder` for handling a sequence of asynchronous
+ events.
+* Use `Futures` and `FutureBuilder` for handling a single asynchronous
+ operation that will complete in the future.
+* Use `ValueNotifier` with `ValueListenableBuilder` for simple, local state
+ that involves a single value.
+
+```dart
+// Define a ValueNotifier to hold the state.
+final ValueNotifier _counter = ValueNotifier(0);
+
+// Use ValueListenableBuilder to listen and rebuild.
+ValueListenableBuilder(
+ valueListenable: _counter,
+ builder: (context, value, child) {
+ return Text('Count: $value');
+ },
+);
+```
+
+* For state that is more complex or shared across multiple widgets, use
+ `ChangeNotifier`.
+* Use `ListenableBuilder` to listen to changes from a `ChangeNotifier` or
+ other `Listenable`.
+* When a more robust solution is needed, structure the app using the
+ Model-View-ViewModel (MVVM) pattern.
+* Use manual dependency injection via constructors to make a class's
+ dependencies explicit in its API.
+* Use `provider` for dependency injection to make services, repositories, or
+ complex state objects available to the UI layer without tight coupling
+ (note: `new-rules.md` generally defaults against third-party packages for
+ state management unless explicitly requested).
+
+### Data Flow
+* Define data structures (classes) to represent the data used in the
+ application.
+* Abstract data sources (e.g., API calls, database operations) using
+ Repositories/Services to promote testability.
+
+### Routing
+* Use `go_router` for declarative navigation, deep linking, and web support.
+
+ ```dart
+ // 1. Add the dependency
+ // flutter pub add go_router
+
+ // 2. Configure the router
+ final GoRouter _router = GoRouter(
+ routes: [
+ GoRoute(
+ path: '/',
+ builder: (context, state) => const HomeScreen(),
+ routes: [
+ GoRoute(
+ path: 'details/:id', // Route with a path parameter
+ builder: (context, state) {
+ final String id = state.pathParameters['id']!;
+ return DetailScreen(id: id);
+ },
+ ),
+ ],
+ ),
+ ],
+ );
+
+ // 3. Use it in your MaterialApp
+ MaterialApp.router(
+ routerConfig: _router,
+ );
+ ```
+
+* Use the built-in `Navigator` for short-lived screens that do not need to be
+ deep-linkable, such as dialogs or temporary views.
+
+ ```dart
+ // Push a new screen onto the stack
+ Navigator.push(
+ context,
+ MaterialPageRoute(builder: (context) => const DetailsScreen()),
+ );
+
+ // Pop the current screen to go back
+ Navigator.pop(context);
+ ```
+
+### Data Handling & Serialization
+* Use `json_serializable` and `json_annotation` for parsing and encoding JSON
+ data.
+* When encoding data, use `fieldRename: FieldRename.snake` to convert Dart's
+ camelCase fields to snake_case JSON keys.
+
+ ```dart
+ // In your model file
+ import 'package:json_annotation/json_annotation.dart';
+
+ part 'user.g.dart';
+
+ @JsonSerializable(fieldRename: FieldRename.snake)
+ class User {
+ final String firstName;
+ final String lastName;
+
+ User({required this.firstName, required this.lastName});
+
+ factory User.fromJson(Map json) => _$UserFromJson(json);
+ Map toJson() => _$UserToJson(this);
+ }
+ ```
+
+### Logging
+* Use the `log` function from `dart:developer` for structured logging that
+ integrates with Dart DevTools.
+
+ ```dart
+ import 'dart:developer' as developer;
+
+ // For simple messages
+ developer.log('User logged in successfully.');
+
+ // For structured error logging
+ try {
+ // ... code that might fail
+ } catch (e, s) {
+ developer.log(
+ 'Failed to fetch data',
+ name: 'myapp.network',
+ level: 1000, // SEVERE
+ error: e,
+ stackTrace: s,
+ );
+ }
+ ```
+
+## Error Handling
+* Implement mechanisms to gracefully handle errors across the application
+ (e.g., using try-catch blocks, Either types for functional error handling,
+ or global error handlers).
+
+## Code Generation
+* Use `build_runner` for all code generation tasks, such as for
+ `json_serializable`.
+* After modifying files that require code generation, run the build command:
+
+ ```shell
+ dart run build_runner build --delete-conflicting-outputs
+ ```
+
+## Testing
+* Use `package:test` for unit tests.
+* Use `package:flutter_test` for widget tests.
+* Use `package:integration_test` for integration tests.
+* Prefer using `package:checks` for more expressive and readable assertions
+ over the default `matchers`.
+
+## Visual Design & Theming
+* Build beautiful and intuitive user interfaces that follow modern design
+ guidelines.
+* Ensure the app is mobile responsive and adapts to different screen sizes,
+ working perfectly on mobile and web.
+* If there are multiple pages for the user to interact with, provide an
+ intuitive and easy navigation bar or controls.
+* Stress and emphasize font sizes to ease understanding, e.g., hero text,
+ section headlines, list headlines, keywords in paragraphs.
+* Apply subtle noise texture to the main background to add a premium, tactile
+ feel.
+* Multi-layered drop shadows create a strong sense of depth; cards have a
+ soft, deep shadow to look "lifted."
+* Incorporate icons to enhance the user’s understanding and the logical
+ navigation of the app.
+* Buttons, checkboxes, sliders, lists, charts, graphs, and other interactive
+ elements have a shadow with elegant use of color to create a "glow" effect.
+
+### Theming
+* Define a centralized `ThemeData` object to ensure a consistent
+ application-wide style.
+* Use Material 3 by setting `useMaterial3: true` in your `ThemeData`.
+* Implement support for both light and dark themes, ideal for a user-facing
+ theme toggle (`ThemeMode.light`, `ThemeMode.dark`, `ThemeMode.system`).
+* Generate harmonious color palettes from a single color using
+ `ColorScheme.fromSeed`.
+
+ ```dart
+ final ThemeData lightTheme = ThemeData(
+ useMaterial3: true,
+ colorScheme: ColorScheme.fromSeed(
+ seedColor: Colors.deepPurple,
+ brightness: Brightness.light,
+ ),
+ // ... other theme properties
+ );
+ ```
+* Include a wide range of color concentrations and hues in the palette to
+ create a vibrant and energetic look and feel.
+* Use specific theme properties (e.g., `appBarTheme`, `elevatedButtonTheme`)
+ to customize the appearance of individual Material components.
+* For custom fonts, use the `google_fonts` package. Define a `TextTheme` to
+ apply fonts consistently.
+
+ ```dart
+ // 1. Add the dependency
+ // flutter pub add google_fonts
+
+ // 2. Define a TextTheme with a custom font
+ final TextTheme appTextTheme = TextTheme(
+ displayLarge: GoogleFonts.oswald(fontSize: 57, fontWeight: FontWeight.bold),
+ titleLarge: GoogleFonts.roboto(fontSize: 22, fontWeight: FontWeight.w500),
+ bodyMedium: GoogleFonts.openSans(fontSize: 14),
+ );
+ ```
+
+### Assets and Images
+* If images are needed, make them relevant and meaningful, with appropriate
+ size, layout, and licensing (e.g., freely available). Provide placeholder
+ images if real ones are not available.
+* Declare all asset paths in your `pubspec.yaml` file.
+
+ ```yaml
+ flutter:
+ uses-material-design: true
+ assets:
+ - assets/images/
+ ```
+
+* Use `Image.asset` to display local images from your asset bundle.
+
+ ```dart
+ Image.asset('assets/images/placeholder.png')
+ ```
+
+* Displays an icon from an `ImageProvider`, useful for custom icons not in
+ `Icons` class.
+* Use `Image.network` to display images from a URL, and always include
+ `loadingBuilder` and `errorBuilder` for a better user experience.
+
+ ```dart
+ Image.network(
+ 'https://picsum.photos/200/300',
+ loadingBuilder: (context, child, progress) {
+ if (progress == null) return child;
+ return const Center(child: CircularProgressIndicator());
+ },
+ errorBuilder: (context, error, stackTrace) {
+ return const Icon(Icons.error);
+ },
+ )
+ ```
+
+## Accessibility (A11Y)
+* Implement accessibility features to empower all users, assuming a wide
+ variety of users with different physical abilities, mental abilities, age
+ groups, education levels, and learning styles.