From ff027701cea7cad1072d39f38747eda1939f32ca Mon Sep 17 00:00:00 2001 From: Amanda Fitch Date: Wed, 20 Aug 2025 12:58:17 -0700 Subject: [PATCH 01/16] Add rules to Create with AI --- site-shared | 2 +- src/content/ai/create-with-ai.md | 121 ++++++++++++++++++++++++++----- 2 files changed, 105 insertions(+), 18 deletions(-) diff --git a/site-shared b/site-shared index 88aa84df953..98457e2c968 160000 --- a/site-shared +++ b/site-shared @@ -1 +1 @@ -Subproject commit 88aa84df953e67b7595b1e214b717f26d81ed538 +Subproject commit 98457e2c968bc6d4981d4a873bba1c35de42e9bb diff --git a/src/content/ai/create-with-ai.md b/src/content/ai/create-with-ai.md index 42acaaa9aea..2af566e5d02 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,86 @@ 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 + +Rules are a key part of the development experience in many +AI-driven editors. The rules provide instructions to an +underlying LLM model, which powers the +AI assistance features. Rules can be used to do many things, +including: + +* Customizing AI behavior +* Enforcing best practices +* Providing project context + +### Editors with rules files + +Several editors, such as Firebase Studio, have rules files +that are useful for providing critical context to LLMs. + +| Environment/IDE | Rules File | Installation Instructions | +| :--- | :--- | :--- | +| Firebase Studio | `airules.md` | [Configure airules.md][] | +| Copilot powered IDEs | `copilot-instructions.md` | [Configure .github/copilot-instructions.md][] | +| Cursor | `cursor.md` | [Configure cursorrules.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 + +### Convert rules between editors + +Firebase Studio has a rules file specifically for Flutter. +If you create a new project with Firebase Studio, you can +get the latest rules for Flutter and convert them so that +they can be used with other editors. + +1. Create a Firebase Studio workspace. + + * Navigate to the [Firebase Studio dashboard][] in + your web browser and sign in. + * In the dashboard, select the Flutter template. + * Name your workspace. + * Create your new workspace. Once the workspace is + ready, the Firebase Studio editor will open with + your new app. + +1. Review or add to `airules.md`. + + * On the left sidebar, click the Explorer icon to + open the File Explorer. + * Navigate to `.idx/airules.md` file and open it. + * Review the contents or add to them. + +1. Convert `airules.md` to another format. + + * If desired, copy the contents of `airules.md` to an + LLM like [Gemini][] and provide a prompt to reformat + the file for another editor. + + Example prompt: + + ```text + Convert the following airules.md file into a + guidelines.md file for JetBrains IDE. Make sure to + use the styles required for a guidelines.md file: + + <> + ``` + +[Firebase Studio dashboard]: https://studio.firebase.google.com/ +[Gemini]: https://gemini.google.com/ From 10b8225f503462f9fea88bd0fd7c7f6c15a3c565 Mon Sep 17 00:00:00 2001 From: Amanda Fitch Date: Wed, 20 Aug 2025 13:00:44 -0700 Subject: [PATCH 02/16] Update TOC --- src/_data/sidenav.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/_data/sidenav.yml b/src/_data/sidenav.yml index a577e07b8d3..6b9a9dea73e 100644 --- a/src/_data/sidenav.yml +++ b/src/_data/sidenav.yml @@ -211,7 +211,7 @@ - title: Create with AI permalink: /ai children: - - title: Overview + - title: Create with AI permalink: /ai/create-with-ai - title: AI Toolkit permalink: /ai-toolkit From 876f1291d9779e48b99fd642d1dbfba1a7987281 Mon Sep 17 00:00:00 2001 From: Amanda Fitch Date: Mon, 25 Aug 2025 10:33:21 -0700 Subject: [PATCH 03/16] Update rules section. --- src/content/ai/create-with-ai.md | 69 +- .../assets/files/flutter-rules-template.md | 651 ++++++++++++++++++ 2 files changed, 683 insertions(+), 37 deletions(-) create mode 100644 src/content/assets/files/flutter-rules-template.md diff --git a/src/content/ai/create-with-ai.md b/src/content/ai/create-with-ai.md index 2af566e5d02..9f8856f585b 100644 --- a/src/content/ai/create-with-ai.md +++ b/src/content/ai/create-with-ai.md @@ -105,7 +105,7 @@ on dart.dev and the [Dart and Flutter MCP repository][dart-mcp-github]. [dart-mcp-github]: {{site.github}}/dart-lang/ai/tree/main/pkgs/dart_mcp_server [dart-mcp-flutter-docs]: #dart-and-flutter-mcp-server -## Rules +## Rules for Flutter and Dart Rules are a key part of the development experience in many AI-driven editors. The rules provide instructions to an @@ -117,16 +117,18 @@ including: * Enforcing best practices * Providing project context -### Editors with rules files +### Environments that support rules -Several editors, such as Firebase Studio, have rules files +Several AI-powered environments have rules files that are useful for providing critical context to LLMs. +Here are a few of the environments that support +rules and the names for their rules files: -| Environment/IDE | Rules File | Installation Instructions | +| Environment | Rules File | Installation Instructions | | :--- | :--- | :--- | -| Firebase Studio | `airules.md` | [Configure airules.md][] | | Copilot powered IDEs | `copilot-instructions.md` | [Configure .github/copilot-instructions.md][] | | Cursor | `cursor.md` | [Configure cursorrules.md][] | +| Firebase Studio | `airules.md` | [Configure airules.md][] | | JetBrains IDEs | `guidelines.md` | [Configure guidelines.md][] | | VS Code | `.instructions.md` | [Configure .instructions.md][] | | Windsurf | `guidelines.md` | [Configure guidelines.md][] | @@ -138,45 +140,38 @@ that are useful for providing critical context to LLMs. [Configure .instructions.md]: https://code.visualstudio.com/docs/copilot/copilot-customization#_custom-instructions [Configure guidelines.md]: https://docs.windsurf.com/windsurf/cascade/memories#rules -### Convert rules between editors - -Firebase Studio has a rules file specifically for Flutter. -If you create a new project with Firebase Studio, you can -get the latest rules for Flutter and convert them so that -they can be used with other editors. +### Create rules for your editor -1. Create a Firebase Studio workspace. - - * Navigate to the [Firebase Studio dashboard][] in - your web browser and sign in. - * In the dashboard, select the Flutter template. - * Name your workspace. - * Create your new workspace. Once the workspace is - ready, the Firebase Studio editor will open with - your new app. +If you want to create Flutter and Dart rules for an +AI-driven environment, follow these steps: -1. Review or add to `airules.md`. +1. Download the attached file, + flutter-rules.md - * On the left sidebar, click the Explorer icon to - open the File Explorer. - * Navigate to `.idx/airules.md` file and open it. - * Review the contents or add to them. +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. -1. Convert `airules.md` to another format. + Example prompt: - * If desired, copy the contents of `airules.md` to an - LLM like [Gemini][] and provide a prompt to reformat - the file for another editor. + ```text + Convert the following flutter-rules.md file into a + guidelines.md file for JetBrains IDE. Make sure to + use the styles required for a guidelines.md file: + ``` - Example prompt: +1. Take the results produced by the LLM and edit until + you have what you need. - ```text - Convert the following airules.md file into a - guidelines.md file for JetBrains IDE. Make sure to - use the styles required for a guidelines.md file: +1. Follow the installation instructions that are provided + by your AI-driven environment to use the rules. You + might need to add the new rules to an existing file + or create a new one in your environment. - <> - ``` +1. Test your AI-driven environment to make sure that the + Flutter and Dart rules are being used. -[Firebase Studio dashboard]: https://studio.firebase.google.com/ [Gemini]: https://gemini.google.com/ 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..d9f65a96d4e --- /dev/null +++ b/src/content/assets/files/flutter-rules-template.md @@ -0,0 +1,651 @@ +# **AI Development Guidelines for Flutter** + +These guidelines define the operational principles and capabilities of an AI agent (e.g., Gemini) interacting with Flutter projects within your environment. The goal is to enable an efficient, automated, and error-resilient application design and development workflow. + +## **Environment & Context Awareness** + +The AI operates within your development environment, which provides a Code OSS-based IDE with deep integration for Flutter. + +* **Project Structure:** The AI assumes a standard Flutter project structure. The primary application entry point is typically lib/main.dart. + +## **Code Modification & Dependency Management** + +The AI is empowered to modify the Flutter codebase and manage its dependencies autonomously based on user requests and detected issues. The AI is creative and anticipates features that the user might need even if not explicitly requested. + +* **Core Code Assumption:** When a user requests a change (e.g., "Add a button to navigate to a new screen"), the AI will primarily focus on modifying the Dart code. lib/main.dart is assumed to be the main entry point, and the AI will infer other relevant files (e.g., creating new widget files, updating pubspec.yaml). +* **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 (e.g., for testing or code generation), it will execute `flutter pub add dev:`. +* **Code Generation (build\_runner):** + 1. When a change introduces a need for code generation (e.g., for freezed classes, json\_serializable models, or riverpod\_generator), the AI will: + 1. Ensure build\_runner is listed in dev\_dependencies in pubspec.yaml. + 2. Automatically execute dart run build\_runner build \--delete-conflicting-outputs to generate necessary files after code modifications that require it. +* **Code Quality:** The AI aims to adhere to Flutter/Dart best practices, including: + * Clean code structure and separation of concerns (e.g., UI logic separate from business logic). + * Meaningful and consistent naming conventions. + * Effective use of const constructors and widgets for performance optimization. + * Appropriate state management solutions (e.g., Provider). + * Avoiding expensive computations or I/O operations directly within build methods. + * Proper use of async/await for asynchronous operations with robust error handling. + +## **Automated Error Detection & Remediation** + +A critical function of the AI is to continuously monitor for and automatically resolve errors to maintain a runnable and correct application state. + +* **Post-Modification Checks:** After *every* code modification (including adding packages, running code generation, or modifying existing files), the AI will: + 1. Monitor the IDE's diagnostics (problem pane) and the terminal output (from flutter run, flutter analyze) for compilation errors, Dart analysis warnings, and runtime exceptions. + 2. Check the preview server's output for rendering issues, application crashes, or unexpected behavior. +* **Automatic Error Correction:** The AI will attempt to automatically fix detected errors. This includes, but is not limited to: + * Syntax errors in Dart code. + * Type mismatches and null-safety violations. + * Unresolved imports or missing package references. + * Linting rule violations (the AI will automatically run flutter format . and address lint warnings). + * When analysis errors are detected, the AI will first attempt to resolve them by running `flutter fix --apply .`. + * Common Flutter-specific issues such as calling setState on an unmounted widget, improper resource disposal in dispose() methods, or incorrect widget tree structures. + * Ensuring proper asynchronous error handling (e.g., adding try-catch blocks for Future operations, using mounted checks before setState). +* **Problem Reporting:** If an error cannot be automatically resolved (e.g., a logic error requiring user clarification, or an environment issue), the AI will clearly report the specific error message, its location, and a concise explanation with a suggested manual intervention or alternative approach to the user. + +## **Material Design Specifics** + +### **Theming** + +The AI will implement and manage a comprehensive and consistent theme for the application, adhering to Material Design 3 principles. This includes defining color schemes, typography, and component styles in a centralized `ThemeData` object. + +#### **Color Schemes (Material 3\)** + +The AI will prioritize using `ColorScheme.fromSeed` to generate harmonious and accessible color palettes from a single seed color. This is the foundation of Material 3 theming and supports dynamic color on platforms like Android. + +#### **Typography and Custom Fonts** + +The AI will use `TextTheme` to define consistent text styles (e.g., `displayLarge`, `titleMedium`, `bodySmall`). For custom fonts, the `google_fonts` package is the recommended approach for its ease of use and vast library of fonts. + +To use `google_fonts`, add it to your project: + +```shell +flutter pub add google_fonts +``` + +*Example `TextTheme` with `google_fonts`:* + +``` +import 'package:google_fonts/google_fonts.dart'; + +final TextTheme myTextTheme = TextTheme( + displayLarge: GoogleFonts.oswald(fontSize: 57, fontWeight: FontWeight.bold), + titleLarge: GoogleFonts.roboto(fontSize: 22, fontWeight: FontWeight.w500), + bodyMedium: GoogleFonts.openSans(fontSize: 14), +); +``` + +#### + +#### **Component Theming** + +To ensure UI consistency, the AI will use specific theme properties (e.g., `appBarTheme`, `elevatedButtonTheme`) to customize the appearance of individual Material components. + +#### **Dark/Light Mode and Theme Toggle** + +The AI will implement support for both light and dark themes. A state management solution like `provider` is ideal for creating a user-facing theme toggle (`ThemeMode.light`, `ThemeMode.dark`, `ThemeMode.system`). + +#### **Full Theming Example** + +The following example demonstrates a complete theme setup using `provider` for a theme toggle and `google_fonts` for typography. + +To use `provider`, add it to your project: + +```shell +flutter pub add provider +``` + +``` +// lib/main.dart +import 'package:flutter/material.dart'; +import 'package:google_fonts/google_fonts.dart'; // Import GoogleFonts +import 'package:provider/provider.dart'; // Import Provider + +void main() { + runApp( + ChangeNotifierProvider( + create: (context) => ThemeProvider(), + child: const MyApp(), + ), + ); +} + +// ThemeProvider class to manage the theme state +class ThemeProvider with ChangeNotifier { + ThemeMode _themeMode = ThemeMode.system; // Default to system theme + + ThemeMode get themeMode => _themeMode; + + void toggleTheme() { + _themeMode = _themeMode == ThemeMode.light ? ThemeMode.dark : ThemeMode.light; + notifyListeners(); + } + + void setSystemTheme() { + _themeMode = ThemeMode.system; + notifyListeners(); + } +} + +class MyApp extends StatelessWidget { + const MyApp({super.key}); + + @override + Widget build(BuildContext context) { + const Color primarySeedColor = Colors.deepPurple; + + // Define a common TextTheme + 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), + ); + + // Light Theme + final ThemeData lightTheme = ThemeData( + useMaterial3: true, + colorScheme: ColorScheme.fromSeed( + seedColor: primarySeedColor, + brightness: Brightness.light, + ), + textTheme: appTextTheme, + appBarTheme: AppBarTheme( + backgroundColor: primarySeedColor, + foregroundColor: Colors.white, + titleTextStyle: GoogleFonts.oswald(fontSize: 24, fontWeight: FontWeight.bold), + ), + elevatedButtonTheme: ElevatedButtonThemeData( + style: ElevatedButton.styleFrom( + foregroundColor: Colors.white, + backgroundColor: primarySeedColor, + shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(8)), + padding: const EdgeInsets.symmetric(horizontal: 24, vertical: 12), + textStyle: GoogleFonts.roboto(fontSize: 16, fontWeight: FontWeight.w500), + ), + ), + ); + + // Dark Theme + final ThemeData darkTheme = ThemeData( + useMaterial3: true, + colorScheme: ColorScheme.fromSeed( + seedColor: primarySeedColor, + brightness: Brightness.dark, + ), + textTheme: appTextTheme, + appBarTheme: AppBarTheme( + backgroundColor: Colors.grey[900], + foregroundColor: Colors.white, + titleTextStyle: GoogleFonts.oswald(fontSize: 24, fontWeight: FontWeight.bold), + ), + elevatedButtonTheme: ElevatedButtonThemeData( + style: ElevatedButton.styleFrom( + foregroundColor: Colors.black, + backgroundColor: primarySeedColor.shade200, + shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(8)), + padding: const EdgeInsets.symmetric(horizontal: 24, vertical: 12), + textStyle: GoogleFonts.roboto(fontSize: 16, fontWeight: FontWeight.w500), + ), + ), + ); + + return Consumer( + builder: (context, themeProvider, child) { + return MaterialApp( + title: 'Flutter Material AI App', + theme: lightTheme, + darkTheme: darkTheme, + themeMode: themeProvider.themeMode, + home: const MyHomePage(), + ); + }, + ); + } +} + +class MyHomePage extends StatelessWidget { + const MyHomePage({super.key}); + + @override + Widget build(BuildContext context) { + final themeProvider = Provider.of(context); + + return Scaffold( + appBar: AppBar( + title: const Text('Material AI Demo'), + actions: [ + IconButton( + icon: Icon(themeProvider.themeMode == ThemeMode.dark ? Icons.light_mode : Icons.dark_mode), + onPressed: () => themeProvider.toggleTheme(), + tooltip: 'Toggle Theme', + ), + IconButton( + icon: const Icon(Icons.auto_mode), + onPressed: () => themeProvider.setSystemTheme(), + tooltip: 'Set System Theme', + ), + ], + ), + body: Center( + child: Column( + mainAxisAlignment: MainAxisAlignment.center, + children: [ + Text('Welcome!', style: Theme.of(context).textTheme.displayLarge), + const SizedBox(height: 20), + Text('This text uses a custom font.', style: Theme.of(context).textTheme.bodyMedium), + const SizedBox(height: 30), + ElevatedButton(onPressed: () {}, child: const Text('Press Me')), + ], + ), + ), + ); + } +} +``` + +### + +### **Assets, Images, and Icons** + +These widgets are used for managing and displaying various types of assets, including images and icons. + +* **Asset Declaration in pubspec.yaml**: Before using assets, they must be declared in the pubspec.yaml file. The AI will prompt the user to ensure this is correctly configured or add it if necessary. + +``` +# In pubspec.yaml +flutter: + uses-material-design: true + assets: + - assets/images/ # Example: entire folder + - assets/icons/my_icon.png # Example: specific file +``` + +* **Image.asset**: Displays an image from the application's asset bundle. + +``` +// Assuming 'assets/images/placeholder.png' is declared in pubspec.yaml +Image.asset( + 'assets/images/placeholder.png', + width: 100, + height: 100, + fit: BoxFit.cover, +) +``` + +* **Image.network**: Displays an image from a URL. + +``` +Image.network( + 'https://picsum.photos/200/300', + width: 200, + height: 300, + fit: BoxFit.cover, + loadingBuilder: (context, child, loadingProgress) { + if (loadingProgress == null) return child; + return Center( + child: CircularProgressIndicator( + value: loadingProgress.progress, + ), + ); + }, + errorBuilder: (context, error, stackTrace) { + return const Icon(Icons.error, color: Colors.red, size: 50); + }, +) +``` + +* **Icon**: Displays a Material Design icon (from Icons class). + +``` +const Icon( + Icons.favorite, + color: Colors.red, + size: 30.0, +) +``` + +* **ImageIcon**: Displays an icon from an ImageProvider (useful for custom icons not in Icons class). + +``` +// Assuming 'assets/icons/custom_icon.png' is declared in pubspec.yaml +ImageIcon( + const AssetImage('assets/icons/custom_icon.png'), + size: 24, + color: Colors.green, +) +``` + +### + +### **Routing and Navigation** + +Flutter provides powerful mechanisms for navigating between different screens (routes) in an application. The AI will utilize and recommend appropriate routing strategies based on the complexity and requirements of the navigation flow. + +* **Basic Imperative Navigation (Navigator)**: For simple navigation stacks, Flutter's built-in Navigator is straightforward. + * **Navigator.push**: Pushes a new route onto the navigator stack. + +``` +// From Screen A to Screen B +Navigator.push( + context, + MaterialPageRoute(builder: (context) => const ScreenB()), +); +``` + +* **Navigator.pop**: Pops the top route off the navigator stack. + +``` +// From Screen B back to Screen A +Navigator.pop(context); +``` + +* **Navigator.pushReplacement**: Replaces the current route with a new one. + +``` +// Replace current screen with a new one (e.g., after login) +Navigator.pushReplacement( + context, + MaterialPageRoute(builder: (context) => const HomeScreen()), +); +``` + +* **Declarative Navigation with go\_router**: For more complex navigation, deep linking, and web support, the go\_router package is a robust and recommended solution. The AI will integrate and configure go\_router when declarative navigation or advanced features like deep linking are required. + To use go\_router, first add it to your project by running: + +```shell +flutter pub add go_router +``` + + **Example go\_router Configuration:** + +``` +// In main.dart or a dedicated router.dart file +import 'package:flutter/material.dart'; +import 'package:go_router/go_router.dart'; + +// Define your routes +final GoRouter _router = GoRouter( + routes: [ + GoRoute( + path: '/', + builder: (BuildContext context, GoRouterState state) { + return const HomeScreen(); // Your home screen + }, + routes: [ + GoRoute( + path: 'details/:id', // Route with a path parameter + builder: (BuildContext context, GoRouterState state) { + final String id = state.pathParameters['id']!; + return DetailScreen(id: id); // Screen to show details + }, + ), + GoRoute( + path: 'settings', + builder: (BuildContext context, GoRouterState state) { + return const SettingsScreen(); // Your settings screen + }, + ), + ], + ), + ], +); + +// In your MaterialApp or CupertinoApp +/* +class MyApp extends StatelessWidget { + const MyApp({super.key}); + + @override + Widget build(BuildContext context) { + return MaterialApp.router( + routerConfig: _router, + title: 'GoRouter Example', + // ... your theme data + ); + } +} +*/ + +// Example screens for the router +class HomeScreen extends StatelessWidget { + const HomeScreen({super.key}); + @override + Widget build(BuildContext context) { + return Scaffold( + appBar: AppBar(title: const Text('Home Screen')), + body: Center( + child: Column( + mainAxisAlignment: MainAxisAlignment.center, + children: [ + ElevatedButton( + onPressed: () => context.go('/details/123'), // Navigate to details with ID + child: const Text('Go to Details 123'), + ), + ElevatedButton( + onPressed: () => context.go('/settings'), // Navigate to settings + child: const Text('Go to Settings'), + ), + ], + ), + ), + ); + } +} + +class DetailScreen extends StatelessWidget { + final String id; + const DetailScreen({super.key, required this.id}); + @override + Widget build(BuildContext context) { + return Scaffold( + appBar: AppBar(title: Text('Detail Screen: $id')), + body: Center( + child: ElevatedButton( + onPressed: () => context.pop(), // Pop back + child: const Text('Go Back'), + ), + ), + ); + } +} + +class SettingsScreen extends StatelessWidget { + const SettingsScreen({super.key}); + @override + Widget build(BuildContext context) { + return Scaffold( + appBar: AppBar(title: const Text('Settings Screen')), + body: Center( + child: ElevatedButton( + onPressed: () => context.pop(), // Pop back + child: const Text('Go Back'), + ), + ), + ); + } +} +``` + +* **Deep Linking**: go\_router handles deep links automatically based on the defined URL paths, allowing specific screens to be opened directly from external sources (e.g., web links, push notifications). +* **Auth Redirects**: The AI can configure go\_router's redirect property to handle authentication flows, ensuring users are redirected to login screens when unauthorized, and back to their intended destination after successful login. + +## **Application Architecture** + +This section outlines the AI's approach to structuring Flutter applications, covering core architectural concepts, recommended patterns, and design principles to ensure maintainability, scalability, and testability. + +### **Architectural Concepts** + +The AI will understand and apply fundamental architectural concepts in Flutter: + +* **Widgets are the UI**: Everything in Flutter's UI is a widget. The AI will compose complex UIs from smaller, reusable widgets. +* **Immutability**: Widgets (especially StatelessWidget) are immutable. When the UI needs to change, Flutter rebuilds the widget tree. +* **State Management**: Understands the importance of managing mutable state. The AI will recommend and apply appropriate state management solutions based on the application's complexity. +* **Separation of Concerns**: Strive to separate UI (widgets), business logic, and data layers to improve code organization, testability, and maintainability. + +### **State Management Recommendations** + +The choice of state management solution depends on the project's scale and complexity. The AI will recommend and use the simplest appropriate tool for the job, starting with Flutter's built-in state management capabilities and using `provider` for more complex scenarios. + +* **Local State Management (Built-in)** + + * **ValueNotifier & ValueListenableBuilder**: For managing the state of a single value. This is the most lightweight and efficient option for simple, local state (e.g., a counter, a boolean flag, or the text in a field). The AI will use `ValueListenableBuilder` to ensure only the widgets that depend on the state are rebuilt. + + *Example:* + +``` +// 1. Define a ValueNotifier to hold the state. +final ValueNotifier _counter = ValueNotifier(0); + +// 2. Use ValueListenableBuilder to listen and rebuild. +ValueListenableBuilder( + valueListenable: _counter, + builder: (context, value, child) { + return Text('Count: $value'); + }, +) + +// 3. Update the value directly. +_counter.value++; +``` + + * **Streams & StreamBuilder**: For handling a sequence of asynchronous events, such as data from a network request, user input, or streams. `StreamBuilder` listens to a stream and rebuilds its UI whenever new data is emitted. + + * **Futures & FutureBuilder**: For handling a single asynchronous operation that will complete in the future, such as fetching data from an API. `FutureBuilder` displays a widget based on the state of the `Future` (e.g., showing a loading spinner while waiting, data on completion, or an error message). + + +* **App-wide State Management & Dependency Injection** + + * **ChangeNotifier & ChangeNotifierProvider**: When state is more complex than a single value or needs to be shared across multiple widgets that are not direct descendants. The AI will use a `ChangeNotifier` to encapsulate the state and business logic, and a `ChangeNotifierProvider` to make it available to the widget tree. This is a foundational pattern for the `provider` package. + + * **Provider**: For dependency injection and managing state that needs to be accessed in multiple places throughout the application. The AI will use `provider` to make services, repositories, or complex state objects available to the UI layer without tight coupling. It is the recommended approach for medium to large applications. + +### **Data Flow and Services** + +The AI will design data flow in a unidirectional manner, typically from a data source (e.g., network, database) through services/repositories to the state management layer, and finally to the UI. + +* **Repositories/Services**: For abstracting data sources (e.g., API calls, database operations). This promotes testability and allows for easy swapping of data sources. +* **Models/Entities**: Define data structures (classes) to represent the data used in the application. +* **Dependency Injection**: Use simple constructor injection or a package like provider to manage dependencies between different layers of the application. + +### **Common Architectural Patterns** + +The AI will apply common architectural patterns to ensure a well-structured application: + +* **MVC (Model-View-Controller) / MVVM (Model-View-ViewModel) / MVI (Model-View-Intent)**: While Flutter's widget-centric nature makes strict adherence to these patterns challenging, the AI will aim for similar separation of concerns. + * **Model**: Data layer and business logic. + * **View**: The UI (widgets). + * **Controller/ViewModel/Presenter**: Handles UI logic, interacts with the model, and updates the view. +* **Layered Architecture**: Organize the project into logical layers such as: + * presentation (UI, widgets, pages) + * domain (business logic, models, use cases) + * data (repositories, data sources, API clients) + * core (shared utilities, common extensions) +* **Feature-first Structure**: Organize code by feature, where each feature has its own presentation, domain, and data subfolders. This improves navigability and scalability for larger projects. + +### **Error Handling and Logging** + +* **Centralized 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). +* **Logging**: Incorporate logging for debugging and monitoring application behavior. + +### **Logging with `dart:developer`** + +For effective debugging and monitoring, the AI will use the `dart:developer` library, which provides structured logging that integrates with Dart DevTools. + +* **Basic Logging**: For simple messages, the `log` function is used. + +``` +import 'dart:developer' as developer; + +developer.log('This is a simple log message.'); +``` + +* **Structured Logging**: For more detailed logs, the `log` function accepts several optional parameters: + + * `name`: A `String` to categorize log messages (e.g., 'my\_app.network'). + * `level`: An `int` for severity (e.g., `800` for `INFO`, `900` for `WARNING`, `1000` for `SEVERE`). + * `error`: An `Object` for logging exceptions. + * `stackTrace`: A `StackTrace` object. + + + *Example:* + +``` +import 'dart:developer' as developer; + +try { + throw 'Something went wrong!'; +} catch (e, s) { + developer.log( + 'An error occurred', + name: 'my_app.network', + level: 900, // WARNING + error: e, + stackTrace: s, + ); +} +``` + +* **Viewing Logs**: Structured logs can be viewed in the "Debug Console" of the IDE or, for a more detailed analysis, in the "Logging" tab of Dart DevTools. This allows for filtering and inspecting log entries, making debugging more efficient. + +## **Test Generation & Execution** + +When requested, the AI will facilitate the creation and execution of tests, ensuring code reliability and validating functionality. + +* **Test Writing:** + * Upon user request for tests (e.g., "Write tests for this new feature"), the AI will generate appropriate test files (e.g., test/\\_test.dart). + * For new functions, methods, or classes, especially those containing business logic, the AI will prioritize writing comprehensive unit tests using the package:test/test.dart framework. + * The AI will automatically set up mocking (e.g., using mockito) to isolate units under test from their dependencies. + * Tests will be designed to cover different input values, edge cases, and error scenarios. +* **Automated Test Execution:** + * After generating or modifying tests, and after any significant code change, the AI will automatically execute the relevant tests using `flutter test` in the terminal. + * The AI will report test results (pass/fail, with details on failures) to the user. + * For broader application validation, the AI can suggest or execute integration tests (`flutter test integration_test/app_test.dart`) when appropriate. +* **Test-Driven Iteration:** The AI supports an iterative test-driven approach, where new features or bug fixes are accompanied by relevant tests, which are then run to validate the changes and provide immediate feedback. + +## **Visual Design** + +**Aesthetics:** The AI always makes a great first impression by creating a unique user experience that incorporates modern components, a visually balanced layout with clean spacing, and polished styles that are easy to understand. + +1. Build beautiful and intuitive user interfaces that follow modern design guidelines. +2. Ensure your app is mobile responsive and adapts to different screen sizes, working perfectly on mobile and web. +3. Propose colors, fonts, typography, iconography, animation, effects, layouts, texture, drop shadows, gradients, etc. +4. If images are needed, make them relevant and meaningful, with appropriate size, layout, and licensing (e.g., freely available). If real images are not available, provide placeholder images. +5. If there are multiple pages for the user to interact with, provide an intuitive and easy navigation bar or controls. + +**Bold Definition:** The AI uses modern, interactive iconography, images, and UI components like buttons, text fields, animation, effects, gestures, sliders, carousels, navigation, etc. + +1. Fonts \- Choose expressive and relevant typography. Stress and emphasize font sizes to ease understanding, e.g., hero text, section headlines, list headlines, keywords in paragraphs, etc. +2. Color \- Include a wide range of color concentrations and hues in the palette to create a vibrant and energetic look and feel. +3. Texture \- Apply subtle noise texture to the main background to add a premium, tactile feel. +4. Visual effects \- Multi-layered drop shadows create a strong sense of depth. Cards have a soft, deep shadow to look "lifted." +5. Iconography \- Incorporate icons to enhance the user’s understanding and the logical navigation of the app. +6. Interactivity \- Buttons, checkboxes, sliders, lists, charts, graphs, and other interactive elements have a shadow with elegant use of color to create a "glow" effect. + +## **Accessibility or A11Y Standards:** 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. + +## **Iterative Development & User Interaction** + +The AI's workflow is iterative, transparent, and responsive to user input. + +* **Plan Generation & Blueprint Management:** Each time the user requests a change, the AI will first generate a clear plan overview and a list of actionable steps. This plan will then be used to **create or update a blueprint.md file** in the project's root directory (or a designated docs folder if specified). + * The blueprint.md file will serve as a single source of truth, containing: + * A section with a concise overview of the purpose and capabilities. + * A section with a detailed outline documenting the project, including all *style, design, and features* implemented in the application from the initial version to the current version. + * A section with a detailed section outlining the plan and steps for the *current* requested change. + * + * Before initiating any new change or at the start of a new chat session, the AI will reference the blueprint.md to ensure full context and understanding of the application's current state and existing features. This ensures consistency and avoids redundant or conflicting modifications. +* **Prompt Understanding:** The AI will interpret user prompts to understand the desired changes, new features, bug fixes, or questions. It will ask clarifying questions if the prompt is ambiguous. +* **Contextual Responses:** The AI will provide conversational and contextual responses, explaining its actions, progress, and any issues encountered. It will summarize changes made. +* **Error Checking Flow:** + 1. **Code Change:** AI applies a code modification. + 2. **Lint/Format:** AI runs `dart format .` and addresses minor lint warnings. + 3. **Dependency Check:** If pubspec.yaml was modified, AI runs `flutter pub get`. + 4. **Code Generation:** If necessary, AI runs `dart run build_runner build --delete-conflicting-outputs`. + 5. **Compile & Analyze:** AI monitors terminal for `flutter analyze` and compilation errors from flutter run (which happens automatically on file save with the preview server). + 6. **Test Execution:** If tests were requested or modified, AI runs `flutter test`. + 7. **Preview Check:** AI observes the preview server for visual and runtime errors. + 8. **Remediation/Report:** If errors are found, AI attempts automatic fixes. If unsuccessful, it reports details to the user. + +This structured approach ensures that the AI can effectively assist in developing and maintaining robust Flutter applications within your environment, making the development process more automated and efficient. From 2eba1e560fa8fb98a5172dc879bcb7bc11262106 Mon Sep 17 00:00:00 2001 From: Amanda Fitch Date: Mon, 25 Aug 2025 11:00:35 -0700 Subject: [PATCH 04/16] Changes to get template to download. --- src/content/ai/create-with-ai.md | 12 ++++++------ .../flutter-rules-template.txt} | 0 2 files changed, 6 insertions(+), 6 deletions(-) rename src/content/{assets/files/flutter-rules-template.md => ai/flutter-rules-template.txt} (100%) diff --git a/src/content/ai/create-with-ai.md b/src/content/ai/create-with-ai.md index 9f8856f585b..0432c6019ea 100644 --- a/src/content/ai/create-with-ai.md +++ b/src/content/ai/create-with-ai.md @@ -146,10 +146,10 @@ If you want to create Flutter and Dart rules for an AI-driven environment, follow these steps: 1. Download the attached file, - flutter-rules.md + flutter-rules-template.txt 1. In an LLM like [Gemini][], attach the - `flutter-rules-template.md` file that you downloaded in + `flutter-rules-template.txt` file that you downloaded in the last step. 1. Provide a prompt to reformat the file for your desired @@ -158,9 +158,9 @@ AI-driven environment, follow these steps: Example prompt: ```text - Convert the following flutter-rules.md file into a - guidelines.md file for JetBrains IDE. Make sure to - use the styles required for a guidelines.md file: + 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. Take the results produced by the LLM and edit until @@ -169,7 +169,7 @@ AI-driven environment, follow these steps: 1. Follow the installation instructions that are provided by your AI-driven environment to use the rules. You might need to add the new rules to an existing file - or create a new one in your environment. + or create a new one in your environment. 1. Test your AI-driven environment to make sure that the Flutter and Dart rules are being used. diff --git a/src/content/assets/files/flutter-rules-template.md b/src/content/ai/flutter-rules-template.txt similarity index 100% rename from src/content/assets/files/flutter-rules-template.md rename to src/content/ai/flutter-rules-template.txt From edb5547c53489b326427430b2cb749f699727eb8 Mon Sep 17 00:00:00 2001 From: Amanda Fitch Date: Mon, 25 Aug 2025 11:47:45 -0700 Subject: [PATCH 05/16] Moved flutter-rules-template.txt back into assets dir. --- src/content/ai/create-with-ai.md | 2 +- src/content/{ai => assets/files}/flutter-rules-template.txt | 0 2 files changed, 1 insertion(+), 1 deletion(-) rename src/content/{ai => assets/files}/flutter-rules-template.txt (100%) diff --git a/src/content/ai/create-with-ai.md b/src/content/ai/create-with-ai.md index 0432c6019ea..505fd7ee20d 100644 --- a/src/content/ai/create-with-ai.md +++ b/src/content/ai/create-with-ai.md @@ -146,7 +146,7 @@ If you want to create Flutter and Dart rules for an AI-driven environment, follow these steps: 1. Download the attached file, - flutter-rules-template.txt + [flutter-rules-template.md](/assets/files/flutter-rules-template) 1. In an LLM like [Gemini][], attach the `flutter-rules-template.txt` file that you downloaded in diff --git a/src/content/ai/flutter-rules-template.txt b/src/content/assets/files/flutter-rules-template.txt similarity index 100% rename from src/content/ai/flutter-rules-template.txt rename to src/content/assets/files/flutter-rules-template.txt From 14f480826de762de6506ab43dcaf0cf74b695aad Mon Sep 17 00:00:00 2001 From: Amanda Fitch Date: Mon, 25 Aug 2025 11:50:14 -0700 Subject: [PATCH 06/16] Changed category name to AI solutions --- src/_data/sidenav.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/_data/sidenav.yml b/src/_data/sidenav.yml index 6b9a9dea73e..36454fac0ba 100644 --- a/src/_data/sidenav.yml +++ b/src/_data/sidenav.yml @@ -208,7 +208,7 @@ - title: Build a news app permalink: /resources/news-toolkit -- title: Create with AI +- title: AI solutions permalink: /ai children: - title: Create with AI From 17ddbe92b43ac72d5e8eac287cb7ce6b1ca20b0f Mon Sep 17 00:00:00 2001 From: Amanda Fitch Date: Mon, 25 Aug 2025 11:53:00 -0700 Subject: [PATCH 07/16] Update link for step 1 in create rules... --- src/content/ai/create-with-ai.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/content/ai/create-with-ai.md b/src/content/ai/create-with-ai.md index 505fd7ee20d..994e6dac8d8 100644 --- a/src/content/ai/create-with-ai.md +++ b/src/content/ai/create-with-ai.md @@ -146,7 +146,7 @@ If you want to create Flutter and Dart rules for an AI-driven environment, follow these steps: 1. Download the attached file, - [flutter-rules-template.md](/assets/files/flutter-rules-template) + flutter-rules-template.txt 1. In an LLM like [Gemini][], attach the `flutter-rules-template.txt` file that you downloaded in From 322b395198e6fca9e1e8b599ce1fbe1997b1f684 Mon Sep 17 00:00:00 2001 From: Amanda Fitch Date: Tue, 26 Aug 2025 15:22:52 -0700 Subject: [PATCH 08/16] Update some wording in the Rules section. --- src/content/ai/create-with-ai.md | 48 +++++++++++++++++--------------- 1 file changed, 25 insertions(+), 23 deletions(-) diff --git a/src/content/ai/create-with-ai.md b/src/content/ai/create-with-ai.md index 994e6dac8d8..4a486cb6232 100644 --- a/src/content/ai/create-with-ai.md +++ b/src/content/ai/create-with-ai.md @@ -107,22 +107,25 @@ on dart.dev and the [Dart and Flutter MCP repository][dart-mcp-github]. ## Rules for Flutter and Dart -Rules are a key part of the development experience in many -AI-driven editors. The rules provide instructions to an -underlying LLM model, which powers the -AI assistance features. Rules can be used to do many things, -including: +`-> Download the Flutter and Dart Rules template <-` -* Customizing AI behavior -* Enforcing best practices -* Providing project context +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. + +You can use the following template to get you +started with rules for Flutter and Dart: +`flutter-rules-template.txt`. ### Environments that support rules -Several AI-powered environments have rules files -that are useful for providing critical context to LLMs. -Here are a few of the environments that support -rules and the names for their rules files: +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 | | :--- | :--- | :--- | @@ -142,10 +145,10 @@ rules and the names for their rules files: ### Create rules for your editor -If you want to create Flutter and Dart rules for an -AI-driven environment, follow these steps: +You can adapt our Flutter and Dart rules template for your +specific environment. To do so, follow these steps: -1. Download the attached file, +1. Download the Flutter and Dart rules template: flutter-rules-template.txt 1. In an LLM like [Gemini][], attach the @@ -163,15 +166,14 @@ AI-driven environment, follow these steps: to use the styles required for a guidelines.md file. ``` -1. Take the results produced by the LLM and edit until - you have what you need. +1. Review the LLM's output and make any necessary + adjustments. -1. Follow the installation instructions that are provided - by your AI-driven environment to use the rules. You - might need to add the new rules to an existing file - or create a new one in your environment. +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. Test your AI-driven environment to make sure that the - Flutter and Dart rules are being used. +1. Verify that your AI assistant is using the new rules to + guide its responses. [Gemini]: https://gemini.google.com/ From 0a6365677562fb1e4e4a540135d21a0dd5b0408b Mon Sep 17 00:00:00 2001 From: Parker Lougheed Date: Tue, 26 Aug 2025 18:43:53 -0500 Subject: [PATCH 09/16] Reupdate site-shared --- site-shared | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/site-shared b/site-shared index 98457e2c968..88aa84df953 160000 --- a/site-shared +++ b/site-shared @@ -1 +1 @@ -Subproject commit 98457e2c968bc6d4981d4a873bba1c35de42e9bb +Subproject commit 88aa84df953e67b7595b1e214b717f26d81ed538 From 277956c6cefd7aca7a73f252da38ee6a16cb56a6 Mon Sep 17 00:00:00 2001 From: Parker Lougheed Date: Tue, 26 Aug 2025 18:45:55 -0500 Subject: [PATCH 10/16] Add a passthrough copy of new assets/files directory --- eleventy.config.ts | 1 + 1 file changed, 1 insertion(+) diff --git a/eleventy.config.ts b/eleventy.config.ts index f86c37ef5fc..dbacbb85223 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', { From 8d526609968efe80e6123f2e85d3d31d0bcc2544 Mon Sep 17 00:00:00 2001 From: Parker Lougheed Date: Tue, 26 Aug 2025 18:53:19 -0500 Subject: [PATCH 11/16] Adjust initial download link --- src/content/ai/create-with-ai.md | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/src/content/ai/create-with-ai.md b/src/content/ai/create-with-ai.md index 4a486cb6232..da8549042e5 100644 --- a/src/content/ai/create-with-ai.md +++ b/src/content/ai/create-with-ai.md @@ -107,7 +107,10 @@ on dart.dev and the [Dart and Flutter MCP repository][dart-mcp-github]. ## Rules for Flutter and Dart -`-> Download the Flutter and Dart Rules template <-` + + + Download the Flutter and Dart rules template + AI-powered editors use rules files to provide context and instructions to an underlying LLM. These files help you: From b4a707c9d287f04c3a13d51b1de984524c4aea3b Mon Sep 17 00:00:00 2001 From: Amanda Fitch Date: Fri, 29 Aug 2025 15:49:11 -0700 Subject: [PATCH 12/16] Move rules into it's own topic. --- src/_data/sidenav.yml | 2 + src/content/ai/ai-rules.md | 81 ++++++++++++++++++++++++++++++++ src/content/ai/create-with-ai.md | 78 ++---------------------------- 3 files changed, 88 insertions(+), 73 deletions(-) create mode 100644 src/content/ai/ai-rules.md diff --git a/src/_data/sidenav.yml b/src/_data/sidenav.yml index 36454fac0ba..c9fd1ea9721 100644 --- a/src/_data/sidenav.yml +++ b/src/_data/sidenav.yml @@ -213,6 +213,8 @@ children: - 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..eda6544567a --- /dev/null +++ b/src/content/ai/ai-rules.md @@ -0,0 +1,81 @@ +--- +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 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][] | +| 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 + +## 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.txt + +1. In an LLM like [Gemini][], attach the + `flutter-rules-template.txt` 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 da8549042e5..e4e4a240ca1 100644 --- a/src/content/ai/create-with-ai.md +++ b/src/content/ai/create-with-ai.md @@ -107,76 +107,8 @@ on dart.dev and the [Dart and Flutter MCP repository][dart-mcp-github]. ## Rules for Flutter and Dart - - - Download the Flutter and Dart rules template - - -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. - -You can use the following template to get you -started with rules for Flutter and Dart: -`flutter-rules-template.txt`. - -### 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][] | -| 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 - -### 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.txt - -1. In an LLM like [Gemini][], attach the - `flutter-rules-template.txt` 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/ +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 From 06a59fc68259562d5d2619c6738827227e57b306 Mon Sep 17 00:00:00 2001 From: John Ryan Date: Thu, 4 Sep 2025 09:16:52 -0700 Subject: [PATCH 13/16] change to markdown file --- eleventy.config.ts | 1 + src/content/ai/ai-rules.md | 6 +++--- ...flutter-rules-template.txt => flutter-rules-template.md} | 0 3 files changed, 4 insertions(+), 3 deletions(-) rename src/content/assets/files/{flutter-rules-template.txt => flutter-rules-template.md} (100%) diff --git a/eleventy.config.ts b/eleventy.config.ts index dbacbb85223..54957a82749 100644 --- a/eleventy.config.ts +++ b/eleventy.config.ts @@ -86,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/content/ai/ai-rules.md b/src/content/ai/ai-rules.md index eda6544567a..a5d10be62f5 100644 --- a/src/content/ai/ai-rules.md +++ b/src/content/ai/ai-rules.md @@ -18,7 +18,7 @@ instructions to an underlying LLM. These files help you: design. * Provide critical project context to the AI. - + Download the Flutter and Dart rules template @@ -51,10 +51,10 @@ 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.txt + flutter-rules-template.md 1. In an LLM like [Gemini][], attach the - `flutter-rules-template.txt` file that you downloaded in + `flutter-rules-template.md` file that you downloaded in the last step. 1. Provide a prompt to reformat the file for your desired diff --git a/src/content/assets/files/flutter-rules-template.txt b/src/content/assets/files/flutter-rules-template.md similarity index 100% rename from src/content/assets/files/flutter-rules-template.txt rename to src/content/assets/files/flutter-rules-template.md From 7b8495bef96177696bd0fea5b356612e1e4f84a9 Mon Sep 17 00:00:00 2001 From: John Ryan Date: Thu, 4 Sep 2025 11:20:38 -0700 Subject: [PATCH 14/16] Update rules file with best-practices --- .../assets/files/flutter-rules-template.md | 783 ++++-------------- 1 file changed, 174 insertions(+), 609 deletions(-) diff --git a/src/content/assets/files/flutter-rules-template.md b/src/content/assets/files/flutter-rules-template.md index d9f65a96d4e..548bd0783fa 100644 --- a/src/content/assets/files/flutter-rules-template.md +++ b/src/content/assets/files/flutter-rules-template.md @@ -1,390 +1,77 @@ -# **AI Development Guidelines for Flutter** - -These guidelines define the operational principles and capabilities of an AI agent (e.g., Gemini) interacting with Flutter projects within your environment. The goal is to enable an efficient, automated, and error-resilient application design and development workflow. - -## **Environment & Context Awareness** - -The AI operates within your development environment, which provides a Code OSS-based IDE with deep integration for Flutter. - -* **Project Structure:** The AI assumes a standard Flutter project structure. The primary application entry point is typically lib/main.dart. - -## **Code Modification & Dependency Management** - -The AI is empowered to modify the Flutter codebase and manage its dependencies autonomously based on user requests and detected issues. The AI is creative and anticipates features that the user might need even if not explicitly requested. - -* **Core Code Assumption:** When a user requests a change (e.g., "Add a button to navigate to a new screen"), the AI will primarily focus on modifying the Dart code. lib/main.dart is assumed to be the main entry point, and the AI will infer other relevant files (e.g., creating new widget files, updating pubspec.yaml). -* **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 (e.g., for testing or code generation), it will execute `flutter pub add dev:`. -* **Code Generation (build\_runner):** - 1. When a change introduces a need for code generation (e.g., for freezed classes, json\_serializable models, or riverpod\_generator), the AI will: - 1. Ensure build\_runner is listed in dev\_dependencies in pubspec.yaml. - 2. Automatically execute dart run build\_runner build \--delete-conflicting-outputs to generate necessary files after code modifications that require it. -* **Code Quality:** The AI aims to adhere to Flutter/Dart best practices, including: - * Clean code structure and separation of concerns (e.g., UI logic separate from business logic). - * Meaningful and consistent naming conventions. - * Effective use of const constructors and widgets for performance optimization. - * Appropriate state management solutions (e.g., Provider). - * Avoiding expensive computations or I/O operations directly within build methods. - * Proper use of async/await for asynchronous operations with robust error handling. - -## **Automated Error Detection & Remediation** - -A critical function of the AI is to continuously monitor for and automatically resolve errors to maintain a runnable and correct application state. - -* **Post-Modification Checks:** After *every* code modification (including adding packages, running code generation, or modifying existing files), the AI will: - 1. Monitor the IDE's diagnostics (problem pane) and the terminal output (from flutter run, flutter analyze) for compilation errors, Dart analysis warnings, and runtime exceptions. - 2. Check the preview server's output for rendering issues, application crashes, or unexpected behavior. -* **Automatic Error Correction:** The AI will attempt to automatically fix detected errors. This includes, but is not limited to: - * Syntax errors in Dart code. - * Type mismatches and null-safety violations. - * Unresolved imports or missing package references. - * Linting rule violations (the AI will automatically run flutter format . and address lint warnings). - * When analysis errors are detected, the AI will first attempt to resolve them by running `flutter fix --apply .`. - * Common Flutter-specific issues such as calling setState on an unmounted widget, improper resource disposal in dispose() methods, or incorrect widget tree structures. - * Ensuring proper asynchronous error handling (e.g., adding try-catch blocks for Future operations, using mounted checks before setState). -* **Problem Reporting:** If an error cannot be automatically resolved (e.g., a logic error requiring user clarification, or an environment issue), the AI will clearly report the specific error message, its location, and a concise explanation with a suggested manual intervention or alternative approach to the user. - -## **Material Design Specifics** - -### **Theming** - -The AI will implement and manage a comprehensive and consistent theme for the application, adhering to Material Design 3 principles. This includes defining color schemes, typography, and component styles in a centralized `ThemeData` object. - -#### **Color Schemes (Material 3\)** - -The AI will prioritize using `ColorScheme.fromSeed` to generate harmonious and accessible color palettes from a single seed color. This is the foundation of Material 3 theming and supports dynamic color on platforms like Android. - -#### **Typography and Custom Fonts** - -The AI will use `TextTheme` to define consistent text styles (e.g., `displayLarge`, `titleMedium`, `bodySmall`). For custom fonts, the `google_fonts` package is the recommended approach for its ease of use and vast library of fonts. - -To use `google_fonts`, add it to your project: - -```shell -flutter pub add google_fonts -``` - -*Example `TextTheme` with `google_fonts`:* - -``` -import 'package:google_fonts/google_fonts.dart'; - -final TextTheme myTextTheme = TextTheme( - displayLarge: GoogleFonts.oswald(fontSize: 57, fontWeight: FontWeight.bold), - titleLarge: GoogleFonts.roboto(fontSize: 22, fontWeight: FontWeight.w500), - bodyMedium: GoogleFonts.openSans(fontSize: 14), -); -``` - -#### - -#### **Component Theming** - -To ensure UI consistency, the AI will use specific theme properties (e.g., `appBarTheme`, `elevatedButtonTheme`) to customize the appearance of individual Material components. - -#### **Dark/Light Mode and Theme Toggle** - -The AI will implement support for both light and dark themes. A state management solution like `provider` is ideal for creating a user-facing theme toggle (`ThemeMode.light`, `ThemeMode.dark`, `ThemeMode.system`). - -#### **Full Theming Example** - -The following example demonstrates a complete theme setup using `provider` for a theme toggle and `google_fonts` for typography. - -To use `provider`, add it to your project: - -```shell -flutter pub add provider -``` - -``` -// lib/main.dart -import 'package:flutter/material.dart'; -import 'package:google_fonts/google_fonts.dart'; // Import GoogleFonts -import 'package:provider/provider.dart'; // Import Provider - -void main() { - runApp( - ChangeNotifierProvider( - create: (context) => ThemeProvider(), - child: const MyApp(), - ), - ); -} - -// ThemeProvider class to manage the theme state -class ThemeProvider with ChangeNotifier { - ThemeMode _themeMode = ThemeMode.system; // Default to system theme - - ThemeMode get themeMode => _themeMode; - - void toggleTheme() { - _themeMode = _themeMode == ThemeMode.light ? ThemeMode.dark : ThemeMode.light; - notifyListeners(); - } - - void setSystemTheme() { - _themeMode = ThemeMode.system; - notifyListeners(); - } -} - -class MyApp extends StatelessWidget { - const MyApp({super.key}); - - @override - Widget build(BuildContext context) { - const Color primarySeedColor = Colors.deepPurple; - - // Define a common TextTheme - 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), - ); - - // Light Theme - final ThemeData lightTheme = ThemeData( - useMaterial3: true, - colorScheme: ColorScheme.fromSeed( - seedColor: primarySeedColor, - brightness: Brightness.light, - ), - textTheme: appTextTheme, - appBarTheme: AppBarTheme( - backgroundColor: primarySeedColor, - foregroundColor: Colors.white, - titleTextStyle: GoogleFonts.oswald(fontSize: 24, fontWeight: FontWeight.bold), - ), - elevatedButtonTheme: ElevatedButtonThemeData( - style: ElevatedButton.styleFrom( - foregroundColor: Colors.white, - backgroundColor: primarySeedColor, - shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(8)), - padding: const EdgeInsets.symmetric(horizontal: 24, vertical: 12), - textStyle: GoogleFonts.roboto(fontSize: 16, fontWeight: FontWeight.w500), - ), - ), - ); - - // Dark Theme - final ThemeData darkTheme = ThemeData( - useMaterial3: true, - colorScheme: ColorScheme.fromSeed( - seedColor: primarySeedColor, - brightness: Brightness.dark, - ), - textTheme: appTextTheme, - appBarTheme: AppBarTheme( - backgroundColor: Colors.grey[900], - foregroundColor: Colors.white, - titleTextStyle: GoogleFonts.oswald(fontSize: 24, fontWeight: FontWeight.bold), - ), - elevatedButtonTheme: ElevatedButtonThemeData( - style: ElevatedButton.styleFrom( - foregroundColor: Colors.black, - backgroundColor: primarySeedColor.shade200, - shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(8)), - padding: const EdgeInsets.symmetric(horizontal: 24, vertical: 12), - textStyle: GoogleFonts.roboto(fontSize: 16, fontWeight: FontWeight.w500), - ), - ), - ); - - return Consumer( - builder: (context, themeProvider, child) { - return MaterialApp( - title: 'Flutter Material AI App', - theme: lightTheme, - darkTheme: darkTheme, - themeMode: themeProvider.themeMode, - home: const MyHomePage(), - ); - }, - ); - } -} - -class MyHomePage extends StatelessWidget { - const MyHomePage({super.key}); - - @override - Widget build(BuildContext context) { - final themeProvider = Provider.of(context); - - return Scaffold( - appBar: AppBar( - title: const Text('Material AI Demo'), - actions: [ - IconButton( - icon: Icon(themeProvider.themeMode == ThemeMode.dark ? Icons.light_mode : Icons.dark_mode), - onPressed: () => themeProvider.toggleTheme(), - tooltip: 'Toggle Theme', - ), - IconButton( - icon: const Icon(Icons.auto_mode), - onPressed: () => themeProvider.setSystemTheme(), - tooltip: 'Set System Theme', - ), - ], - ), - body: Center( - child: Column( - mainAxisAlignment: MainAxisAlignment.center, - children: [ - Text('Welcome!', style: Theme.of(context).textTheme.displayLarge), - const SizedBox(height: 20), - Text('This text uses a custom font.', style: Theme.of(context).textTheme.bodyMedium), - const SizedBox(height: 30), - ElevatedButton(onPressed: () {}, child: const Text('Press Me')), - ], - ), - ), - ); - } -} -``` - -### - -### **Assets, Images, and Icons** - -These widgets are used for managing and displaying various types of assets, including images and icons. - -* **Asset Declaration in pubspec.yaml**: Before using assets, they must be declared in the pubspec.yaml file. The AI will prompt the user to ensure this is correctly configured or add it if necessary. - -``` -# In pubspec.yaml -flutter: - uses-material-design: true - assets: - - assets/images/ # Example: entire folder - - assets/icons/my_icon.png # Example: specific file -``` - -* **Image.asset**: Displays an image from the application's asset bundle. - -``` -// Assuming 'assets/images/placeholder.png' is declared in pubspec.yaml -Image.asset( - 'assets/images/placeholder.png', - width: 100, - height: 100, - fit: BoxFit.cover, -) -``` - -* **Image.network**: Displays an image from a URL. +# AI Development Guidelines 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. + +## 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, methods, + and functions. +* Write clear comments for complex or non-obvious code. Avoid over-commenting. +* Use `async` / `await` instead of `Future.then()` for asynchronous + operations. +* Use pattern matching features where they simplify the code. + +## Flutter Best Practices +* Prefer composing smaller widgets over extending existing ones. +* 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 + +### State Management +* Default to Flutter's built-in state management solutions. Do not use a + third-party package unless explicitly requested. +* 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); -``` -Image.network( - 'https://picsum.photos/200/300', - width: 200, - height: 300, - fit: BoxFit.cover, - loadingBuilder: (context, child, loadingProgress) { - if (loadingProgress == null) return child; - return Center( - child: CircularProgressIndicator( - value: loadingProgress.progress, - ), - ); - }, - errorBuilder: (context, error, stackTrace) { - return const Icon(Icons.error, color: Colors.red, size: 50); +// Use ValueListenableBuilder to listen and rebuild. +ValueListenableBuilder( + valueListenable: _counter, + builder: (context, value, child) { + return Text('Count: $value'); }, -) -``` - -* **Icon**: Displays a Material Design icon (from Icons class). - -``` -const Icon( - Icons.favorite, - color: Colors.red, - size: 30.0, -) -``` - -* **ImageIcon**: Displays an icon from an ImageProvider (useful for custom icons not in Icons class). - -``` -// Assuming 'assets/icons/custom_icon.png' is declared in pubspec.yaml -ImageIcon( - const AssetImage('assets/icons/custom_icon.png'), - size: 24, - color: Colors.green, -) -``` - -### - -### **Routing and Navigation** - -Flutter provides powerful mechanisms for navigating between different screens (routes) in an application. The AI will utilize and recommend appropriate routing strategies based on the complexity and requirements of the navigation flow. - -* **Basic Imperative Navigation (Navigator)**: For simple navigation stacks, Flutter's built-in Navigator is straightforward. - * **Navigator.push**: Pushes a new route onto the navigator stack. - -``` -// From Screen A to Screen B -Navigator.push( - context, - MaterialPageRoute(builder: (context) => const ScreenB()), -); -``` - -* **Navigator.pop**: Pops the top route off the navigator stack. - -``` -// From Screen B back to Screen A -Navigator.pop(context); -``` - -* **Navigator.pushReplacement**: Replaces the current route with a new one. - -``` -// Replace current screen with a new one (e.g., after login) -Navigator.pushReplacement( - context, - MaterialPageRoute(builder: (context) => const HomeScreen()), ); ``` - -* **Declarative Navigation with go\_router**: For more complex navigation, deep linking, and web support, the go\_router package is a robust and recommended solution. The AI will integrate and configure go\_router when declarative navigation or advanced features like deep linking are required. - To use go\_router, first add it to your project by running: - -```shell -flutter pub add go_router -``` - - **Example go\_router Configuration:** - -``` -// In main.dart or a dedicated router.dart file -import 'package:flutter/material.dart'; -import 'package:go_router/go_router.dart'; - -// Define your routes +* 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. + +### 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: (BuildContext context, GoRouterState state) { - return const HomeScreen(); // Your home screen - }, + builder: (context, state) => const HomeScreen(), routes: [ GoRoute( path: 'details/:id', // Route with a path parameter - builder: (BuildContext context, GoRouterState state) { + builder: (context, state) { final String id = state.pathParameters['id']!; - return DetailScreen(id: id); // Screen to show details - }, - ), - GoRoute( - path: 'settings', - builder: (BuildContext context, GoRouterState state) { - return const SettingsScreen(); // Your settings screen + return DetailScreen(id: id); }, ), ], @@ -392,260 +79,138 @@ final GoRouter _router = GoRouter( ], ); -// In your MaterialApp or CupertinoApp -/* -class MyApp extends StatelessWidget { - const MyApp({super.key}); - - @override - Widget build(BuildContext context) { - return MaterialApp.router( - routerConfig: _router, - title: 'GoRouter Example', - // ... your theme data - ); - } -} -*/ - -// Example screens for the router -class HomeScreen extends StatelessWidget { - const HomeScreen({super.key}); - @override - Widget build(BuildContext context) { - return Scaffold( - appBar: AppBar(title: const Text('Home Screen')), - body: Center( - child: Column( - mainAxisAlignment: MainAxisAlignment.center, - children: [ - ElevatedButton( - onPressed: () => context.go('/details/123'), // Navigate to details with ID - child: const Text('Go to Details 123'), - ), - ElevatedButton( - onPressed: () => context.go('/settings'), // Navigate to settings - child: const Text('Go to Settings'), - ), - ], - ), - ), - ); - } -} - -class DetailScreen extends StatelessWidget { - final String id; - const DetailScreen({super.key, required this.id}); - @override - Widget build(BuildContext context) { - return Scaffold( - appBar: AppBar(title: Text('Detail Screen: $id')), - body: Center( - child: ElevatedButton( - onPressed: () => context.pop(), // Pop back - child: const Text('Go Back'), - ), - ), - ); - } -} - -class SettingsScreen extends StatelessWidget { - const SettingsScreen({super.key}); - @override - Widget build(BuildContext context) { - return Scaffold( - appBar: AppBar(title: const Text('Settings Screen')), - body: Center( - child: ElevatedButton( - onPressed: () => context.pop(), // Pop back - child: const Text('Go Back'), - ), - ), - ); - } -} -``` - -* **Deep Linking**: go\_router handles deep links automatically based on the defined URL paths, allowing specific screens to be opened directly from external sources (e.g., web links, push notifications). -* **Auth Redirects**: The AI can configure go\_router's redirect property to handle authentication flows, ensuring users are redirected to login screens when unauthorized, and back to their intended destination after successful login. - -## **Application Architecture** - -This section outlines the AI's approach to structuring Flutter applications, covering core architectural concepts, recommended patterns, and design principles to ensure maintainability, scalability, and testability. - -### **Architectural Concepts** - -The AI will understand and apply fundamental architectural concepts in Flutter: - -* **Widgets are the UI**: Everything in Flutter's UI is a widget. The AI will compose complex UIs from smaller, reusable widgets. -* **Immutability**: Widgets (especially StatelessWidget) are immutable. When the UI needs to change, Flutter rebuilds the widget tree. -* **State Management**: Understands the importance of managing mutable state. The AI will recommend and apply appropriate state management solutions based on the application's complexity. -* **Separation of Concerns**: Strive to separate UI (widgets), business logic, and data layers to improve code organization, testability, and maintainability. - -### **State Management Recommendations** - -The choice of state management solution depends on the project's scale and complexity. The AI will recommend and use the simplest appropriate tool for the job, starting with Flutter's built-in state management capabilities and using `provider` for more complex scenarios. - -* **Local State Management (Built-in)** - - * **ValueNotifier & ValueListenableBuilder**: For managing the state of a single value. This is the most lightweight and efficient option for simple, local state (e.g., a counter, a boolean flag, or the text in a field). The AI will use `ValueListenableBuilder` to ensure only the widgets that depend on the state are rebuilt. - - *Example:* - +// 3. Use it in your MaterialApp +MaterialApp.router( + routerConfig: _router, +); ``` -// 1. Define a ValueNotifier to hold the state. -final ValueNotifier _counter = ValueNotifier(0); - -// 2. Use ValueListenableBuilder to listen and rebuild. -ValueListenableBuilder( - valueListenable: _counter, - builder: (context, value, child) { - return Text('Count: $value'); - }, -) +* 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()), +); -// 3. Update the value directly. -_counter.value++; +// Pop the current screen to go back +Navigator.pop(context); ``` - * **Streams & StreamBuilder**: For handling a sequence of asynchronous events, such as data from a network request, user input, or streams. `StreamBuilder` listens to a stream and rebuilds its UI whenever new data is emitted. - - * **Futures & FutureBuilder**: For handling a single asynchronous operation that will complete in the future, such as fetching data from an API. `FutureBuilder` displays a widget based on the state of the `Future` (e.g., showing a loading spinner while waiting, data on completion, or an error message). - - -* **App-wide State Management & Dependency Injection** - - * **ChangeNotifier & ChangeNotifierProvider**: When state is more complex than a single value or needs to be shared across multiple widgets that are not direct descendants. The AI will use a `ChangeNotifier` to encapsulate the state and business logic, and a `ChangeNotifierProvider` to make it available to the widget tree. This is a foundational pattern for the `provider` package. - - * **Provider**: For dependency injection and managing state that needs to be accessed in multiple places throughout the application. The AI will use `provider` to make services, repositories, or complex state objects available to the UI layer without tight coupling. It is the recommended approach for medium to large applications. - -### **Data Flow and Services** - -The AI will design data flow in a unidirectional manner, typically from a data source (e.g., network, database) through services/repositories to the state management layer, and finally to the UI. - -* **Repositories/Services**: For abstracting data sources (e.g., API calls, database operations). This promotes testability and allows for easy swapping of data sources. -* **Models/Entities**: Define data structures (classes) to represent the data used in the application. -* **Dependency Injection**: Use simple constructor injection or a package like provider to manage dependencies between different layers of the application. - -### **Common Architectural Patterns** - -The AI will apply common architectural patterns to ensure a well-structured application: +### 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'; -* **MVC (Model-View-Controller) / MVVM (Model-View-ViewModel) / MVI (Model-View-Intent)**: While Flutter's widget-centric nature makes strict adherence to these patterns challenging, the AI will aim for similar separation of concerns. - * **Model**: Data layer and business logic. - * **View**: The UI (widgets). - * **Controller/ViewModel/Presenter**: Handles UI logic, interacts with the model, and updates the view. -* **Layered Architecture**: Organize the project into logical layers such as: - * presentation (UI, widgets, pages) - * domain (business logic, models, use cases) - * data (repositories, data sources, API clients) - * core (shared utilities, common extensions) -* **Feature-first Structure**: Organize code by feature, where each feature has its own presentation, domain, and data subfolders. This improves navigability and scalability for larger projects. +part 'user.g.dart'; -### **Error Handling and Logging** +@JsonSerializable(fieldRename: FieldRename.snake) +class User { + final String firstName; + final String lastName; -* **Centralized 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). -* **Logging**: Incorporate logging for debugging and monitoring application behavior. + User({required this.firstName, required this.lastName}); -### **Logging with `dart:developer`** + factory User.fromJson(Map json) => _$UserFromJson(json); + Map toJson() => _$UserToJson(this); +}``` -For effective debugging and monitoring, the AI will use the `dart:developer` library, which provides structured logging that integrates with Dart DevTools. - -* **Basic Logging**: For simple messages, the `log` function is used. - -``` +### Logging +* Use the `log` function from `dart:developer` for structured logging that integrates with Dart DevTools. +```dart import 'dart:developer' as developer; -developer.log('This is a simple log message.'); -``` - -* **Structured Logging**: For more detailed logs, the `log` function accepts several optional parameters: - - * `name`: A `String` to categorize log messages (e.g., 'my\_app.network'). - * `level`: An `int` for severity (e.g., `800` for `INFO`, `900` for `WARNING`, `1000` for `SEVERE`). - * `error`: An `Object` for logging exceptions. - * `stackTrace`: A `StackTrace` object. - - - *Example:* - -``` -import 'dart:developer' as developer; +// For simple messages +developer.log('User logged in successfully.'); +// For structured error logging try { - throw 'Something went wrong!'; + // ... code that might fail } catch (e, s) { developer.log( - 'An error occurred', - name: 'my_app.network', - level: 900, // WARNING + 'Failed to fetch data', + name: 'myapp.network', + level: 1000, // SEVERE error: e, stackTrace: s, ); } ``` -* **Viewing Logs**: Structured logs can be viewed in the "Debug Console" of the IDE or, for a more detailed analysis, in the "Logging" tab of Dart DevTools. This allows for filtering and inspecting log entries, making debugging more efficient. - -## **Test Generation & Execution** - -When requested, the AI will facilitate the creation and execution of tests, ensuring code reliability and validating functionality. - -* **Test Writing:** - * Upon user request for tests (e.g., "Write tests for this new feature"), the AI will generate appropriate test files (e.g., test/\\_test.dart). - * For new functions, methods, or classes, especially those containing business logic, the AI will prioritize writing comprehensive unit tests using the package:test/test.dart framework. - * The AI will automatically set up mocking (e.g., using mockito) to isolate units under test from their dependencies. - * Tests will be designed to cover different input values, edge cases, and error scenarios. -* **Automated Test Execution:** - * After generating or modifying tests, and after any significant code change, the AI will automatically execute the relevant tests using `flutter test` in the terminal. - * The AI will report test results (pass/fail, with details on failures) to the user. - * For broader application validation, the AI can suggest or execute integration tests (`flutter test integration_test/app_test.dart`) when appropriate. -* **Test-Driven Iteration:** The AI supports an iterative test-driven approach, where new features or bug fixes are accompanied by relevant tests, which are then run to validate the changes and provide immediate feedback. - -## **Visual Design** - -**Aesthetics:** The AI always makes a great first impression by creating a unique user experience that incorporates modern components, a visually balanced layout with clean spacing, and polished styles that are easy to understand. - -1. Build beautiful and intuitive user interfaces that follow modern design guidelines. -2. Ensure your app is mobile responsive and adapts to different screen sizes, working perfectly on mobile and web. -3. Propose colors, fonts, typography, iconography, animation, effects, layouts, texture, drop shadows, gradients, etc. -4. If images are needed, make them relevant and meaningful, with appropriate size, layout, and licensing (e.g., freely available). If real images are not available, provide placeholder images. -5. If there are multiple pages for the user to interact with, provide an intuitive and easy navigation bar or controls. - -**Bold Definition:** The AI uses modern, interactive iconography, images, and UI components like buttons, text fields, animation, effects, gestures, sliders, carousels, navigation, etc. - -1. Fonts \- Choose expressive and relevant typography. Stress and emphasize font sizes to ease understanding, e.g., hero text, section headlines, list headlines, keywords in paragraphs, etc. -2. Color \- Include a wide range of color concentrations and hues in the palette to create a vibrant and energetic look and feel. -3. Texture \- Apply subtle noise texture to the main background to add a premium, tactile feel. -4. Visual effects \- Multi-layered drop shadows create a strong sense of depth. Cards have a soft, deep shadow to look "lifted." -5. Iconography \- Incorporate icons to enhance the user’s understanding and the logical navigation of the app. -6. Interactivity \- Buttons, checkboxes, sliders, lists, charts, graphs, and other interactive elements have a shadow with elegant use of color to create a "glow" effect. - -## **Accessibility or A11Y Standards:** 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. - -## **Iterative Development & User Interaction** - -The AI's workflow is iterative, transparent, and responsive to user input. +## 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 + +### Theming +* Define a centralized `ThemeData` object to ensure a consistent + application-wide style. +* Use Material 3 by setting `useMaterial3: true` in your `ThemeData`. +* 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 +); +``` +* 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 -* **Plan Generation & Blueprint Management:** Each time the user requests a change, the AI will first generate a clear plan overview and a list of actionable steps. This plan will then be used to **create or update a blueprint.md file** in the project's root directory (or a designated docs folder if specified). - * The blueprint.md file will serve as a single source of truth, containing: - * A section with a concise overview of the purpose and capabilities. - * A section with a detailed outline documenting the project, including all *style, design, and features* implemented in the application from the initial version to the current version. - * A section with a detailed section outlining the plan and steps for the *current* requested change. - * - * Before initiating any new change or at the start of a new chat session, the AI will reference the blueprint.md to ensure full context and understanding of the application's current state and existing features. This ensures consistency and avoids redundant or conflicting modifications. -* **Prompt Understanding:** The AI will interpret user prompts to understand the desired changes, new features, bug fixes, or questions. It will ask clarifying questions if the prompt is ambiguous. -* **Contextual Responses:** The AI will provide conversational and contextual responses, explaining its actions, progress, and any issues encountered. It will summarize changes made. -* **Error Checking Flow:** - 1. **Code Change:** AI applies a code modification. - 2. **Lint/Format:** AI runs `dart format .` and addresses minor lint warnings. - 3. **Dependency Check:** If pubspec.yaml was modified, AI runs `flutter pub get`. - 4. **Code Generation:** If necessary, AI runs `dart run build_runner build --delete-conflicting-outputs`. - 5. **Compile & Analyze:** AI monitors terminal for `flutter analyze` and compilation errors from flutter run (which happens automatically on file save with the preview server). - 6. **Test Execution:** If tests were requested or modified, AI runs `flutter test`. - 7. **Preview Check:** AI observes the preview server for visual and runtime errors. - 8. **Remediation/Report:** If errors are found, AI attempts automatic fixes. If unsuccessful, it reports details to the user. +// 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), +); +``` -This structured approach ensures that the AI can effectively assist in developing and maintaining robust Flutter applications within your environment, making the development process more automated and efficient. +### Assets and Images +* 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') +``` +* 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); + }, +) +``` From 8fef2d5e6fd158158ee5f095fc1a119e3cb7a8c7 Mon Sep 17 00:00:00 2001 From: John Ryan Date: Thu, 4 Sep 2025 11:48:23 -0700 Subject: [PATCH 15/16] Update rules file with complete set of rules --- .../assets/files/flutter-rules-template.md | 324 +++++++++++------- 1 file changed, 208 insertions(+), 116 deletions(-) diff --git a/src/content/assets/files/flutter-rules-template.md b/src/content/assets/files/flutter-rules-template.md index 548bd0783fa..507488f66bd 100644 --- a/src/content/assets/files/flutter-rules-template.md +++ b/src/content/assets/files/flutter-rules-template.md @@ -1,23 +1,45 @@ -# AI Development Guidelines for Flutter +# 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, methods, - and functions. +* 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. -* Use `async` / `await` instead of `Future.then()` for asynchronous - operations. +* 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. @@ -27,12 +49,19 @@ practices. 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); @@ -45,6 +74,7 @@ ValueListenableBuilder( }, ); ``` + * For state that is more complex or shared across multiple widgets, use `ChangeNotifier`. * Use `ListenableBuilder` to listen to changes from a `ChangeNotifier` or @@ -53,101 +83,124 @@ ValueListenableBuilder( 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(), + + ```dart + // 1. Add the dependency + // flutter pub add go_router + + // 2. Configure the router + final GoRouter _router = GoRouter( routes: [ GoRoute( - path: 'details/:id', // Route with a path parameter - builder: (context, state) { - final String id = state.pathParameters['id']!; - return DetailScreen(id: id); - }, + 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, + ); + ``` -// 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); -``` + ```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'; + ```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); + } + ``` -@JsonSerializable(fieldRename: FieldRename.snake) -class User { - final String firstName; - final String lastName; +### Logging +* Use the `log` function from `dart:developer` for structured logging that + integrates with Dart DevTools. - User({required this.firstName, required this.lastName}); + ```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, + ); + } + ``` - 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 -``` + + ```shell + dart run build_runner build --delete-conflicting-outputs + ``` ## Testing * Use `package:test` for unit tests. @@ -157,60 +210,99 @@ dart run build_runner build --delete-conflicting-outputs 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 -); -``` + + ```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), -); -``` + + ```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/ -``` + + ```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') -``` + + ```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); - }, -) -``` + + ```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. From dd4fc3b4935e94e103e2b554757a6d77beab1b96 Mon Sep 17 00:00:00 2001 From: Amanda Fitch <18406675+antfitch@users.noreply.github.com> Date: Thu, 4 Sep 2025 14:15:13 -0700 Subject: [PATCH 16/16] Update ai-rules.md Add Gemini CLI to this list. --- src/content/ai/ai-rules.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/src/content/ai/ai-rules.md b/src/content/ai/ai-rules.md index a5d10be62f5..2138e6beb55 100644 --- a/src/content/ai/ai-rules.md +++ b/src/content/ai/ai-rules.md @@ -34,6 +34,7 @@ corresponding rule file names: | 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][] | @@ -44,6 +45,7 @@ corresponding rule file names: [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