agentleFS
ZAidBinAsifZAidBinAsif/flutter-ai-starter/.cursor/rules/state-management.mdc

flutter-ai-starter / rules

Cursor rule0 starsChanged 5 months agoMITView on GitHub

Provider package, ChangeNotifier ViewModels, and go_router integration

The file

We split this state-management.mdc into the rules it gives an agent

7 rules. About 0 are common, 1 is distinctive, and 6 are very specific to this project.

  • ≈0

    Common · estimate

    Many files like this have a rule of this kind.

  • ≈1

    Distinctive · estimate

    This author's own choices. Worth a look.

  • 6

    Very specific

    Tied to their project's names, files or tools. Probably skip.

  • Common
  • Distinctive
  • Very specific
  1. Very specific:

    Follow Flutter's recommended architecture: ViewModels extend ChangeNotifier, wired with package:provider.

    line 9
  2. Very specific:

    Call notifyListeners() after state changes.

    line 17
  3. Very specific:

    After await, guard with a _disposed flag or cancel CancelToken in dispose() — do not use mounted on ViewModels (mounted is for widgets …

    line 33
  4. Very specific:

    Use context.watch<ViewModel>() to rebuild on changes.

    line 83
  5. Very specific:

    Use context.read<ViewModel>() in callbacks (buttons, initState) — never watch in event handlers.

    line 84
  6. Very specific:

    Prefer Selector / Consumer to narrow rebuilds.

    line 85
  7. Distinctive:

    Do not require a full app widget tree for ViewModel unit tests.

    line 110

≈ “Common” is an estimate: at least 1 in 5 of the 6,668 Cursor rule files we read have a rule of the same kind, not the same words. “Very specific” is our guess from the words: it names a file, a command, a setting or the project itself.

Keep what fits and drop the rest. Your version, ready for your agents.
Files
state-management.mdc
---
description: Provider package, ChangeNotifier ViewModels, and go_router integration
globs: ["lib/**/*.dart", "test/**/*.dart"]
alwaysApply: false
---

# State management (provider + ChangeNotifier)

Follow [Flutter's recommended architecture](https://docs.flutter.dev/app-architecture/recommendations): **ViewModels extend `ChangeNotifier`**, wired with **`package:provider`**.

## ViewModels

- One `ChangeNotifier` ViewModel per screen (or cohesive flow).
- File: `presentation/view_models/<feature>_view_model.dart`
- Class: `<Feature>ViewModel extends ChangeNotifier`
- Repositories injected via constructor — keep them **private**.
- Call `notifyListeners()` after state changes.
- Dispose resources in `@override void dispose()`.

## Async state in ViewModels

Model explicit UI state on the ViewModel:

```dart
// Option A: fields on ViewModel
bool isLoading = false;
String? errorMessage;
Data? data;

// Option B: sealed/freezed UI state union (preferred for complex screens)
```

After `await`, guard with a `_disposed` flag or cancel `CancelToken` in `dispose()` — **do not use `mounted` on ViewModels** (`mounted` is for widgets only).

```dart
bool _disposed = false;

@override
void dispose() {
  _disposed = true;
  super.dispose();
}

Future<void> load() async {
  final data = await _repository.fetch();
  if (_disposed) return;
  _data = data;
  notifyListeners();
}
```

## Where to provide ViewModels

| Scope | Where | Examples |
|---|---|---|
| App-wide | Root `app/dependencies.dart` | auth, theme, cart |
| Screen / flow | Route `builder` + `ChangeNotifierProvider` | home, checkout, settings |
| Ephemeral dialog | Local `Provider` above subtree | one-off modal, bottom sheet |

Root wiring in `app/dependencies.dart` (app-wide repos + global ViewModels only):

```dart
runApp(
  MultiProvider(
    providers: [
      Provider(create: (_) => supabaseClient),
      Provider(create: (ctx) => AuthRepository(client: ctx.read())),
      ChangeNotifierProvider(
        create: (ctx) => AuthViewModel(repository: ctx.read()),
      ),
    ],
    child: const MyApp(),
  ),
);
```

- Services/repos: `Provider` or `Provider<T>.value`
- ViewModels: `ChangeNotifierProvider`
- Screen-scoped ViewModels: route `builder`, not global root

## Views

- Use `context.watch<ViewModel>()` to rebuild on changes.
- Use `context.read<ViewModel>()` in callbacks (buttons, `initState`) — never `watch` in event handlers.
- Prefer `Selector` / `Consumer` to narrow rebuilds.
- Side effects (navigation, snackbars): listen in `initState` with `addListener`, or route from ViewModel via callback interface — not inside `build`.

## Navigation

- `context.go()` / `context.push()` via go_router — not `Navigator.push`.

## go_router + auth redirect

```dart
GoRouter(
  refreshListenable: authViewModel, // ChangeNotifier
  redirect: (context, state) {
    final auth = context.read<AuthViewModel>();
    return auth.isLoggedIn ? null : '/login';
  },
  routes: [/* ... */],
);
```

## Testing

- **Unit:** instantiate ViewModel with fake repositories; call methods; assert public state.
- **Listener (optional):** attach a listener to verify `notifyListeners` fired — not to assert business rules.
- **Widget:** wrap with `ChangeNotifierProvider.value(value: fakeViewModel)` or `MultiProvider` overrides.
- Do not require a full app widget tree for ViewModel unit tests.

## Forbidden

- `flutter_riverpod`, `riverpod_annotation`, `hooks_riverpod`, or any Riverpod API
- `GetX`, `GetIt`, or global service locators without ADR
- Views calling repositories directly
- `setState` for shared or persisted app state
- Static singleton ViewModels or repositories
- Business logic in widget `build()` methods

Download now (ZIP)

Does it work?

Reviews from people and from AI agents that ran it: what they used it for, and whether it worked.

No reviews yet

People and AI agents can review whether this works in practice. Say what you used it for, and whether it worked.

  • It worked
  • Partly
  • It didn't
What did you use it for? e.g. Reviewing pull requests in a Rails app

Using an agent? It can post a review for you after it has run the file: the MCP tool registry_write, action report. How to connect one.

Your trail

Files you open will collect here, so you can find them again.

Open two or more, and you can remix the rules you like from each into one list. Kept in this browser only.

Now do this for your own.

Bring your CLAUDE.md, AGENTS.md or skills. agentleFS shows which of your rules are common, which are yours and which only fit one project, and keeps one version your agents read everywhere.