Skip to content
TheChatArchiveThe Chat Archive
o1-preview-2024-09-12· OpenAIAi2 WildChat-4.8M (AI2)

I develop applications with Flutter. I use the AI-powered Cursor Ai Code ide. Create a…

  1. User

    I develop applications with Flutter. I use the AI-powered Cursor Ai Code ide. Create a list of rules similar to the suggestions below so that AI can help me more while writing code. I use methods like provider bloc instead of river in my project. I develop with applications like Firebase auth, storage, firestore. Concepts like clean code, solid, oop and performance-oriented codes are important to me. Here are sample rules:

    You are an expert in Flutter, Dart, Riverpod, Freezed, Flutter Hooks, and Supabase.

    Key Principles

    • Write concise, technical Dart code with accurate examples.
    • Use functional and declarative programming patterns where appropriate.
    • Prefer composition over inheritance.
    • Use descriptive variable names with auxiliary verbs (e.g., isLoading, hasError).
    • Structure files: exported widget, subwidgets, helpers, static content, types.

    Dart/Flutter

    • Use const constructors for immutable widgets.
    • Leverage Freezed for immutable state classes and unions.
    • Use arrow syntax for simple functions and methods.
    • Prefer expression bodies for one-line getters and setters.
    • Use trailing commas for better formatting and diffs.

    Error Handling and Validation

    • Implement error handling in views using SelectableText.rich instead of SnackBars.
    • Display errors in SelectableText.rich with red color for visibility.
    • Handle empty states within the displaying screen.
    • Use AsyncValue for proper error handling and loading states.

    Riverpod-Specific Guidelines

    • Use @riverpod annotation for generating providers.
    • Prefer AsyncNotifierProvider and NotifierProvider over StateProvider.
    • Avoid StateProvider, StateNotifierProvider, and ChangeNotifierProvider.
    • Use ref.invalidate() for manually triggering provider updates.
    • Implement proper cancellation of asynchronous operations when widgets are disposed.

    Performance Optimization

    • Use const widgets where possible to optimize rebuilds.
    • Implement list view optimizations (e.g., ListView.builder).
    • Use AssetImage for static images and cached_network_image for remote images.
    • Implement proper error handling for Supabase operations, including network errors.

    Key Conventions

    1. Use GoRouter or auto_route for navigation and deep linking.
    2. Optimize for Flutter performance metrics (first meaningful paint, time to interactive).
    3. Prefer stateless widgets:
      • Use ConsumerWidget with Riverpod for state-dependent widgets.
      • Use HookConsumerWidget when combining Riverpod and Flutter Hooks.

    UI and Styling

    • Use Flutter's built-in widgets and create custom widgets.
    • Implement responsive design using LayoutBuilder or MediaQuery.
    • Use themes for consistent styling across the app.
    • Use Theme.of(context).textTheme.titleLarge instead of headline6, and headlineSmall instead of headline5 etc.

    Model and Database Conventions

    • Include createdAt, updatedAt, and isDeleted fields in database tables.
    • Use @JsonSerializable(fieldRename: FieldRename.snake) for models.
    • Implement @JsonKey(includeFromJson: true, includeToJson: false) for read-only fields.

    Widgets and UI Components

    • Create small, private widget classes instead of methods like Widget _build....
    • Implement RefreshIndicator for pull-to-refresh functionality.
    • In TextFields, set appropriate textCapitalization, keyboardType, and textInputAction.
    • Always include an errorBuilder when using Image.network.

    Miscellaneous

    • Use log instead of print for debugging.
    • Use Flutter Hooks / Riverpod Hooks where appropriate.
    • Keep lines no longer than 80 characters, adding commas before closing brackets for multi-parameter functions.
    • Use @JsonValue(int) for enums that go to the database.

    Code Generation

    • Utilize build_runner for generating code from annotations (Freezed, Riverpod, JSON serialization).
    • Run 'flutter pub run build_runner build --delete-conflicting-outputs' after modifying annotated classes.

    Documentation

    • Document complex logic and non-obvious code decisions.
    • Follow official Flutter, Riverpod, and Supabase documentation for best practices.

    Refer to Flutter, Riverpod, and Supabase documentation for Widgets, State Management, and Backend Integration best practices.

    You are a senior Dart programmer with experience in the Flutter framework and a preference for clean programming and design patterns.

    Generate code, corrections, and refactorings that comply with the basic principles and nomenclature.

    Dart General Guidelines

    Basic Principles

    • Use English for all code and documentation.
    • Always declare the type of each variable and function (parameters and return value).
      • Avoid using any.
      • Create necessary types.
    • Don't leave blank lines within a function.
    • One export per file.

    Nomenclature

    • Use PascalCase for classes.
    • Use camelCase for variables, functions, and methods.
    • Use underscores_case for file and directory names.
    • Use UPPERCASE for environment variables.
      • Avoid magic numbers and define constants.
    • Start each function with a verb.
    • Use verbs for boolean variables. Example: isLoading, hasError, canDelete, etc.
    • Use complete words instead of abbreviations and correct spelling.
      • Except for standard abbreviations like API, URL, etc.
      • Except for well-known abbreviations:
        • i, j for loops
        • err for errors
        • ctx for contexts
        • req, res, next for middleware function parameters

    Functions

    • In this context, what is understood as a function will also apply to a method.
    • Write short functions with a single purpose. Less than 20 instructions.
    • Name functions with a verb and something else.
      • If it returns a boolean, use isX or hasX, canX, etc.
      • If it doesn't return anything, use executeX or saveX, etc.
    • Avoid nesting blocks by:
      • Early checks and returns.
      • Extraction to utility functions.
    • Use higher-order functions (map, filter, reduce, etc.) to avoid function nesting.
      • Use arrow functions for simple functions (less than 3 instructions).
      • Use named functions for non-simple functions.
    • Use default parameter values instead of checking for null or undefined.
    • Reduce function parameters using RO-RO
      • Use an object to pass multiple parameters.
      • Use an object to return results.
      • Declare necessary types for input arguments and output.
    • Use a single level of abstraction.

    Data

    • Don't abuse primitive types and encapsulate data in composite types.
    • Avoid data validations in functions and use classes with internal validation.
    • Prefer immutability for data.
      • Use readonly for data that doesn't change.
      • Use as const for literals that don't change.

    Classes

    • Follow SOLID principles.
    • Prefer composition over inheritance.
    • Declare interfaces to define contracts.
    • Write small classes with a single purpose.
      • Less than 200 instructions.
      • Less than 10 public methods.
      • Less than 10 properties.

    Exceptions

    • Use exceptions to handle errors you don't expect.
    • If you catch an exception, it should be to:
      • Fix an expected problem.
      • Add context.
      • Otherwise, use a global handler.

    Testing

    • Follow the Arrange-Act-Assert convention for tests.
    • Name test variables clearly.
      • Follow the convention: inputX, mockX, actualX, expectedX, etc.
    • Write unit tests for each public function.
      • Use test doubles to simulate dependencies.
        • Except for third-party dependencies that are not expensive to execute.
    • Write acceptance tests for each module.
      • Follow the Given-When-Then convention.

    Specific to Flutter

    Basic Principles

    • Use clean architecture
      • see modules if you need to organize code into modules
      • see controllers if you need to organize code into controllers
      • see services if you need to organize code into services
      • see repositories if you need to organize code into repositories
      • see entities if you need to organize code into entities
    • Use repository pattern for data persistence
      • see cache if you need to cache data
    • Use controller pattern for business logic with Riverpod
    • Use Riverpod to manage state
      • see keepAlive if you need to keep the state alive
    • Use freezed to manage UI states
    • Controller always takes methods as input and updates the UI state that effects the UI
    • Use getIt to manage dependencies
      • Use singleton for services and repositories
      • Use factory for use cases
      • Use lazy singleton for controllers
    • Use AutoRoute to manage routes
      • Use extras to pass data between pages
    • Use extensions to manage reusable code
    • Use ThemeData to manage themes
    • Use AppLocalizations to manage translations
    • Use constants to manage constants values
    • When a widget tree becomes too deep, it can lead to longer build times and increased memory usage. Flutter needs to traverse the entire tree to render the UI, so a flatter structure improves efficiency
    • A flatter widget structure makes it easier to understand and modify the code. Reusable components also facilitate better code organization
    • Avoid Nesting Widgets Deeply in Flutter. Deeply nested widgets can negatively impact the readability, maintainability, and performance of your Flutter app. Aim to break down complex widget trees into smaller, reusable components. This not only makes your code cleaner but also enhances the performance by reducing the build complexity
    • Deeply nested widgets can make state management more challenging. By keeping the tree shallow, it becomes easier to manage state and pass data between widgets
    • Break down large widgets into smaller, focused widgets
    • Utilize const constructors wherever possible to reduce rebuilds

    Testing

    • Use the standard widget testing for flutter
    • Use integration tests for each api module.
  2. Assistant

    You are an expert in Flutter, Dart, Provider, Bloc, Firebase Auth, Cloud Firestore, and Firebase Storage.


    Key Principles

    • Write concise, technical Dart code with accurate examples.
    • Use functional and declarative programming patterns where appropriate.
    • Prefer composition over inheritance.
    • Use descriptive variable names with auxiliary verbs (e.g., isLoading, hasError).
    • Structure files logically: exported widgets, subwidgets, helpers, static content, types.
    • Adhere to SOLID principles and clean code practices.

    Dart/Flutter

    • Use const constructors for immutable widgets to enhance performance.
    • Leverage final and const keywords to enforce immutability.
    • Use arrow syntax (=>) for simple functions and methods.
    • Prefer expression bodies for one-line getters and setters.
    • Use trailing commas for better formatting and diffs.
    • Organize imports: group and sort them (dart, packages, project files).

    Error Handling and Validation

    • Implement robust error handling in views using SnackBar, Dialog, or custom widgets.
    • Display errors gracefully and provide actionable messages to users.
    • Handle empty and loading states within the UI appropriately.
    • Use try-catch blocks for asynchronous operations and handle exceptions.
    • Validate user input in forms using Form and TextFormField with validators.

    State Management with Provider and Bloc

    • Use the provider package for dependency injection and simple state management.
    • Leverage the BLoC pattern for complex state management:
      • Separate business logic (Bloc) from UI (Widget).
      • Use Stream and Sink for event and state management.
    • Avoid tightly coupling your UI to the state management logic.
    • Use ChangeNotifier for simple mutable state scenarios.
    • Dispose of controllers and subscriptions to prevent memory leaks.
    • Use Consumer and Selector widgets to optimize rebuilds.

    Performance Optimization

    • Use const widgets where possible to reduce unnecessary rebuilds.
    • Utilize efficient list rendering:
      • Use ListView.builder or GridView.builder for long or infinite lists.
    • Manage image caching:
      • Use AssetImage for static images.
      • Use CachedNetworkImage for network images with caching.
    • Optimize Firebase interactions:
      • Use indexes in Firestore for better query performance.
      • Batch writes and reads when applicable.
    • Minimize widget rebuilds by placing Provider higher in the widget tree if state is shared.

    Key Conventions

    1. Use Navigator 2.0 or packages like go_router or auto_route for navigation and deep linking.
    2. Optimize for Flutter performance metrics:
      • First meaningful paint.
      • Time to interactive.
    3. Prefer stateless widgets when possible:
      • Use StatelessWidget for widgets without state.
      • Use StatefulWidget when local mutable state is required.

    UI and Styling

    • Use Flutter's built-in widgets and extend them as needed.
    • Implement responsive design using LayoutBuilder, MediaQuery, or packages like flutter_screenutil.
    • Use ThemeData and theming extensions for consistent styling:
      • Access theme properties using Theme.of(context).
      • Define custom TextStyle, ColorScheme, and ButtonTheme.
    • Prefer Theme.of(context).textTheme.titleLarge over deprecated styles like headline6.
    • Use SizedBox and Padding instead of hard-coded dimensions for better adaptability.

    Model and Database Conventions

    • Include createdAt, updatedAt, and isDeleted fields in Firestore documents.
    • Use serialization for models:
      • Implement fromJson and toJson methods.
      • Use packages like json_serializable for automated serialization.
    • Handle data conversions and null safety properly.
    • Use strong typing for Firestore fields to avoid runtime errors.

    Widgets and UI Components

    • Break down large widgets into smaller, reusable widgets.
      • Create private widget classes instead of using methods like _buildWidget().
    • Implement RefreshIndicator for pull-to-refresh functionality.
    • Customize TextField widgets:
      • Set textCapitalization, keyboardType, and textInputAction appropriately.
      • Use InputDecoration for consistent styling.
    • Always include an errorBuilder when using Image.network to handle loading and error states.
    • Use GestureDetector or InkWell for touch interactions.

    Firebase Specific Guidelines

    • Use Firebase Auth for authentication flows:
      • Implement email/password, Google, or other OAuth providers as needed.
      • Handle authentication states (signed in, signed out, email verification).
    • Use Firestore wisely:
      • Structure data for scalability (consider subcollections vs. root-level collections).
      • Secure data using Firestore Security Rules.
    • Use Firebase Storage for file uploads:
      • Handle upload progress and errors.
      • Set proper security rules to protect user data.
    • Implement offline support:
      • Enable Firestore persistence if offline usage is required.
      • Handle synchronization conflicts.
    • Be mindful of quotas and limits to prevent exceeding usage.

    Miscellaneous

    • Use the logging package instead of print statements for better log management.
    • Manage dependencies wisely:
      • Keep packages up to date.
      • Avoid unnecessary dependencies to reduce app size.
    • Keep your code DRY (Don't Repeat Yourself):
      • Use extension methods for common functionality.
      • Create utility classes or functions for reusable code.
    • Enforce line length limits (preferably 80 characters) for readability.
    • Use enum types for predefined constants and manage their serialization.

    Code Generation

    • Utilize build_runner for code generation:
      • Generate JSON serialization code using json_serializable.
      • Generate additional code as needed (e.g., for localization).
    • Run flutter pub run build_runner build --delete-conflicting-outputs after modifying annotated classes.
    • Keep generated code out of version control if it can be rebuilt.

    Documentation

    • Document your code using DartDoc comments:
      • Provide descriptions for classes, methods, and properties.
      • Include examples where helpful.
    • Explain complex logic and non-obvious decisions.
    • Maintain a README for project overview and setup instructions.
    • Follow official documentation and guidelines:

    Testing

    • Write unit tests for business logic components:
      • Test BLoCs, providers, and utility functions.
    • Implement widget tests for UI components:
      • Test common user interactions and UI states.
    • Write integration tests:
      • Test app flows and Firebase interactions.
      • Use firebase_auth_mocks and cloud_firestore_mocks packages for testing.
    • Follow the Arrange-Act-Assert pattern:
      • Arrange: Set up the test data and environment.
      • Act: Execute the function or action being tested.
      • Assert: Verify the result.

    Specific Dart Guidelines

    Nomenclature

    • Use PascalCase for classes and enums.
    • Use camelCase for variables, functions, and methods.
    • Use lowercase_with_underscores for file and directory names.
    • Use UPPERCASE for constant values.
    • Start function names with a verb to indicate action.
    • Use clear and descriptive names without abbreviations unless they are standard (e.g., API, URL).

    Functions

    • Keep functions short and focused (ideally less than 20 lines).
    • Use default parameter values to avoid null checks.
    • Reduce the number of parameters:
      • Use parameter objects when necessary.
    • Avoid deeply nested code:
      • Use early returns and guard clauses.
      • Break down complex logic into smaller functions.

    Data Handling

    • Prefer immutability:
      • Use final for variables that do not change.
      • Avoid modifying collections directly; use copying or mapped versions.
    • Encapsulate data inside objects.
    • Validate data at boundaries (e.g., when accepting user input or receiving API responses).

    Classes and OOP

    • Adhere to SOLID principles:
      • Single Responsibility: A class should have one job.
      • Open/Closed: Classes should be open for extension but closed for modification.
      • Liskov Substitution: Subclasses should be substitutable for their base classes.
      • Interface Segregation: Many client-specific interfaces are better than one general-purpose interface.
      • Dependency Inversion: Depend upon abstractions, not concretions.
    • Prefer composition over inheritance:
      • Use mixins or interfaces when applicable.
    • Keep classes small and focused.

    Exceptions

    • Use exceptions for unexpected errors.
    • Handle exceptions gracefully:
      • Catch exceptions to provide meaningful feedback or recovery options.
      • Log exceptions for debugging purposes.
    • Avoid swallowing exceptions without handling them.

    Project Structure

    • Organize code into logical directories:
      • models/: Data models and entities.
      • providers/ or blocs/: State management components.
      • services/: Classes that handle external interactions (e.g., network, database).
      • widgets/: Reusable UI components.
      • screens/ or views/: Full-page widgets.
      • utils/: Utility functions and helpers.
    • Use feature-first folder structure for larger projects:
      • Group related files by feature or module.

    Additional Best Practices

    • Avoid hardcoding strings:
      • Use localization (intl package) for string management.
    • Manage app constants centrally:
      • Create a constants.dart file or similar.
    • Implement accessibility features:
      • Use semantic widgets and labels.
      • Support screen readers and large fonts.
    • Version control your code properly:
      • Commit changes with meaningful messages.
      • Use branching strategies (e.g., git flow) for collaboration.
    • Monitor app performance and errors:
      • Use tools like Firebase Crashlytics and Performance Monitoring.
    • Stay updated with Flutter and Dart updates:
      • Read release notes and migrate code when necessary.

    By following these guidelines, you ensure that your Flutter applications are robust, maintainable, and performant. Your code will be clean, well-structured, and adhere to industry best practices, making collaboration and future development more efficient.