Cursor rules for structuring Flutter widgets as small const-friendly classes, keeping setState local, building lazy lists and verifying with analyze and widget tests.
.cursor/rules/flutter-widget-structure.mdc. Downloaded files need to be placed in that repository path.---
description: "Cursor rules for structuring Flutter widgets as small const-friendly classes, keeping setState local, building lazy lists and verifying with analyze and widget tests."
globs: "**/*"
alwaysApply: false
---
# Flutter Widget Structure
Applies to: Flutter widgets and screens (`lib/**/*.dart`) and their widget tests (`test/**/*.dart`).
Version baseline: checked against the Flutter 3.47 documentation and Effective Dart. Read `pubspec.yaml` (Flutter/Dart SDK constraints, state-management packages, `flutter_lints` or `very_good_analysis`) and `analysis_options.yaml` first, and follow the project's existing state-management approach.
## Composition
- Build screens from small widget classes, each with one job (layout section, list item, form field group).
- To reuse a piece of UI, extract a `StatelessWidget` or `StatefulWidget` class, not a method or function that returns a widget. Classes get their own `BuildContext`, can be `const`, and let Flutter skip rebuilding them.
- Keep widgets decoupled: pass data and callbacks in through the constructor instead of reaching into global state or a parent's state.
- Put one public widget per file when it is used from more than one place; small private helper widgets (`_Avatar`) can stay in the file that uses them.
## Naming and files
- Types in `UpperCamelCase`, members and variables in `lowerCamelCase`, files and directories in `lowercase_with_underscores` (`user_card.dart`).
- Group by feature (`lib/features/profile/...`) or follow the existing structure.
## Types
- Annotate public APIs: constructor parameters, fields and return types of public methods.
- Let the analyzer infer obvious local variables (`final count = items.length;`); Effective Dart recommends against annotating initialized locals.
- Prefer `final` fields and `const` constructors for widgets.
## State
- Use `StatelessWidget` when the widget only renders its inputs. Use `StatefulWidget` when it owns mutable UI state (text controllers, animation controllers, toggles), and dispose controllers in `dispose()`.
- Keep `setState` as low in the tree as possible: move the changing part into its own `StatefulWidget` so only that subtree rebuilds.
- For state shared across screens, use the project's state-management package (Provider, Riverpod, Bloc or similar) rather than passing setters through many layers.
- Implement `didUpdateWidget` only when the state must react to a changed constructor argument (for example, restart an animation or resubscribe).
## Layout
- Compose with `Row`, `Column`, `Stack`, `Expanded`, `Flexible` and `Padding`/`SizedBox` for spacing.
- `Positioned` inside a `Stack` is the right tool for overlays such as badges; avoid hard-coded pixel offsets for whole-screen layout because they break on other screen sizes and text scales.
- Use `LayoutBuilder` or `MediaQuery.sizeOf(context)` for responsive breakpoints.
## Performance
- Mark widgets and widget subtrees `const` when their inputs are compile-time constants; the lint `prefer_const_constructors` points these out.
- Build long or unbounded lists with `ListView.builder`/`GridView.builder` so items are created lazily.
- Avoid the `Opacity` widget in animations; use `AnimatedOpacity` or `FadeTransition`.
- Do not do expensive work (parsing, sorting large lists, I/O) inside `build()`; compute it once in state or upstream.
- Profile in profile mode with Flutter DevTools before optimizing; deep widget trees are normal in Flutter and are not a problem by themselves.
```dart
import 'package:flutter/material.dart';
class User {
const User({required this.id, required this.name});
final String id;
final String name;
}
class UserList extends StatelessWidget {
const UserList({super.key, required this.users, required this.onSelect});
final List<User> users;
final ValueChanged<User> onSelect;
@override
Widget build(BuildContext context) {
if (users.isEmpty) {
return const Center(child: Text('No users yet'));
}
return ListView.builder(
itemCount: users.length,
itemBuilder: (context, index) {
final user = users[index];
return UserTile(
key: ValueKey(user.id),
user: user,
onTap: () => onSelect(user),
);
},
);
}
}
class UserTile extends StatelessWidget {
const UserTile({super.key, required this.user, required this.onTap});
final User user;
final VoidCallback onTap;
@override
Widget build(BuildContext context) {
return ListTile(title: Text(user.name), onTap: onTap);
}
}
```
## Verify before finishing
Run these when they are available in the project:
- `dart format --set-exit-if-changed .`
- `flutter analyze` (no new warnings)
- `flutter test`, with a widget test for each new widget (`testWidgets`, `find.text`, `tester.tap`)
Cursor rules for Next.js 14+ App Router projects updated for Next.js 16 with async params, validated Route Handlers, generateMetadata and proxy.ts in place of middleware.
Cursor rules for strict TypeScript: compiler checks beyond strict, interfaces vs type aliases, real type guards, discriminated unions, utility types and branded IDs.
Cursor rules for Tailwind CSS v4: automatic class sorting, mobile-first breakpoints, CVA variants with merging, class-based dark mode via @custom-variant, and CSS-first @theme configuration.
Cursor
coding
Illustrative input and expected result. This example is a verification guide, not a recorded model run.
Content reviewed .
A Flutter 3.x app using flutter_lints has this rule attached to lib/ while a developer asks Cursor to build a selectable user list.
Create lib/user_list.dart with a widget that shows users by name, shows an empty-state message when there are none, and calls back with the tapped user. Add a widget test.
Illustrative; not a recorded model run. A const-constructible UserList StatelessWidget that takes users and a ValueChanged<User> callback, returns a const empty-state Center/Text or a ListView.builder of UserTile widget classes keyed by user id (no helper method returning widgets), dart-format clean code, and testWidgets cases for the empty state and for tapping an item.
Cursor applies project rules stored as .mdc files in .cursor/rules. Each rule's frontmatter (description, globs, alwaysApply) decides whether it is always included, attached to matching files, chosen by the agent from its description, or only used when you @-mention it. Cursor also reads AGENTS.md in the project root and subdirectories for plain-Markdown instructions.
.cursor/rules/flutter-widget-structure.mdcStarting point, not a tested configuration for your repository. Attached when files matching the globs are in context (alwaysApply: false with globs). Review the instructions, adapt the file paths and run your project's existing checks.
---
description: "Flutter Widget Structure: Composition, State and Rebuild Scope project conventions"
globs: "**/*"
alwaysApply: false
---
# Flutter Widget Structure
Applies to: Flutter widgets and screens (`lib/**/*.dart`) and their widget tests (`test/**/*.dart`).
Version baseline: checked against the Flutter 3.47 documentation and Effective Dart. Read `pubspec.yaml` (Flutter/Dart SDK constraints, state-management packages, `flutter_lints` or `very_good_analysis`) and `analysis_options.yaml` first, and follow the project's existing state-management approach.
## Composition
- Build screens from small widget classes, each with one job (layout section, list item, form field group).
- To reuse a piece of UI, extract a `StatelessWidget` or `StatefulWidget` class, not a method or function that returns a widget. Classes get their own `BuildContext`, can be `const`, and let Flutter skip rebuilding them.
- Keep widgets decoupled: pass data and callbacks in through the constructor instead of reaching into global state or a parent's state.
- Put one public widget per file when it is used from more than one place; small private helper widgets (`_Avatar`) can stay in the file that uses them.
## Naming and files
- Types in `UpperCamelCase`, members and variables in `lowerCamelCase`, files and directories in `lowercase_with_underscores` (`user_card.dart`).
- Group by feature (`lib/features/profile/...`) or follow the existing structure.
## Types
- Annotate public APIs: constructor parameters, fields and return types of public methods.
- Let the analyzer infer obvious local variables (`final count = items.length;`); Effective Dart recommends against annotating initialized locals.
- Prefer `final` fields and `const` constructors for widgets.
## State
- Use `StatelessWidget` when the widget only renders its inputs. Use `StatefulWidget` when it owns mutable UI state (text controllers, animation controllers, toggles), and dispose controllers in `dispose()`.
- Keep `setState` as low in the tree as possible: move the changing part into its own `StatefulWidget` so only that subtree rebuilds.
- For state shared across screens, use the project's state-management package (Provider, Riverpod, Bloc or similar) rather than passing setters through many layers.
- Implement `didUpdateWidget` only when the state must react to a changed constructor argument (for example, restart an animation or resubscribe).
## Layout
- Compose with `Row`, `Column`, `Stack`, `Expanded`, `Flexible` and `Padding`/`SizedBox` for spacing.
- `Positioned` inside a `Stack` is the right tool for overlays such as badges; avoid hard-coded pixel offsets for whole-screen layout because they break on other screen sizes and text scales.
- Use `LayoutBuilder` or `MediaQuery.sizeOf(context)` for responsive breakpoints.
## Performance
- Mark widgets and widget subtrees `const` when their inputs are compile-time constants; the lint `prefer_const_constructors` points these out.
- Build long or unbounded lists with `ListView.builder`/`GridView.builder` so items are created lazily.
- Avoid the `Opacity` widget in animations; use `AnimatedOpacity` or `FadeTransition`.
- Do not do expensive work (parsing, sorting large lists, I/O) inside `build()`; compute it once in state or upstream.
- Profile in profile mode with Flutter DevTools before optimizing; deep widget trees are normal in Flutter and are not a problem by themselves.
```dart
import 'package:flutter/material.dart';
class User {
const User({required this.id, required this.name});
final String id;
final String name;
}
class UserList extends StatelessWidget {
const UserList({super.key, required this.users, required this.onSelect});
final List<User> users;
final ValueChanged<User> onSelect;
@override
Widget build(BuildContext context) {
if (users.isEmpty) {
return const Center(child: Text('No users yet'));
}
return ListView.builder(
itemCount: users.length,
itemBuilder: (context, index) {
final user = users[index];
return UserTile(
key: ValueKey(user.id),
user: user,
onTap: () => onSelect(user),
);
},
);
}
}
class UserTile extends StatelessWidget {
const UserTile({super.key, required this.user, required this.onTap});
final User user;
final VoidCallback onTap;
@override
Widget build(BuildContext context) {
return ListTile(title: Text(user.name), onTap: onTap);
}
}
```
## Verify before finishing
Run these when they are available in the project:
- `dart format --set-exit-if-changed .`
- `flutter analyze` (no new warnings)
- `flutter test`, with a widget test for each new widget (`testWidgets`, `find.text`, `tester.tap`)
Ask for a small change to one matching file. Check the tool's loaded context or instruction view, inspect the diff for the requested convention, and run the relevant build or test. A well-formatted file does not guarantee the model follows every instruction.
Cursor's docs recommend keeping individual rules under 500 lines and splitting large rules into composable ones. Cursor's documentation states that it supports AGENTS.md in the project root and in subdirectories. Use AGENTS.md for plain-Markdown instructions you also want other tools to read, and .mdc rules when you need Cursor's scoping options (globs, description-based selection, always-apply).
Documentation checked 2026-11-05: Cursor docs: Rules
Cursor rules for Next.js 14+ App Router projects updated for Next.js 16 with async params, validated Route Handlers, generateMetadata and proxy.ts in place of middleware.
Cursor rules for strict TypeScript: compiler checks beyond strict, interfaces vs type aliases, real type guards, discriminated unions, utility types and branded IDs.
Cursor rules for Tailwind CSS v4: automatic class sorting, mobile-first breakpoints, CVA variants with merging, class-based dark mode via @custom-variant, and CSS-first @theme configuration.