# Reject stale Flutter search results after a newer query or disposal

mounted prevents state updates after disposal, but two requests can race while the widget remains mounted. A generation token identifies the current request and rejects an older result that completes later.

Save this requirement in Perch and check it after each agent edit. The rule gives your agent a named check to run, a finding to repair, and the same command to recheck.

## Implement the Flutter boundary

Save this illustrative integration module as `lib/order_search.dart`.

```dart
import 'package:flutter/widgets.dart';

class OrderSearch extends StatefulWidget {
  final Future<List<String>> Function(String) search;
  const OrderSearch({super.key, required this.search});
  @override State<OrderSearch> createState() => OrderSearchState();
}

class OrderSearchState extends State<OrderSearch> {
  int generation = 0;
  List<String> orders = [];
  Object? failure;
  Future<void> load(String query) async {
    final requestGeneration = ++generation;
    try {
      final result = await widget.search(query);
      if (!mounted || requestGeneration != generation) return;
      setState(() { orders = result; failure = null; });
    } catch (error) {
      if (!mounted || requestGeneration != generation) return;
      setState(() { failure = error; });
    }
  }
  @override void didUpdateWidget(covariant OrderSearch oldWidget) {
    super.didUpdateWidget(oldWidget);
    if (oldWidget.search != widget.search) { generation++; orders = []; failure = null; }
  }
  @override Widget build(BuildContext context) => Text(failure == null ? orders.join(', ') : 'Search failed');
}
```

The order, inventory, or resource-lifetime scenario is adapted from Perch’s public [order-service source at commit 4af67af](https://github.com/lakeday-org/perch/blob/4af67af46d76ac99398d61c7ad0a45441760d4dc/test/fixtures/order-service/inventory.py). This Flutter implementation is an illustrative adaptation.

## Integrate with your application

Use this State with a search adapter that applies server authorization and reports failures. The sample exposes load for the focused test; wire it to your input/controller in the application. Cancel underlying work where the client supports it, and dispose owned timers/subscriptions. The error branch uses the same generation/mounted check, and changing the search adapter invalidates pending completions. Trigger a fresh load when the query or adapter changes.



## Exercise the boundary and failure paths

| Scenario | Expected outcome |
| --- | --- |
| A starts, B starts, B resolves then A | Only B displayed |
| Widget disposed before result | No setState |
| Mounted but old request completes | Result ignored by generation |
| Current request fails | Current error shown without stale results |

Add regression tests for these cases in your existing Flutter test project. Use separate connections or deliberately reordered completion where the case involves concurrency; a sequential happy-path test does not exercise that failure. Run the test command after creating the matching test file or suite:

```sh
flutter test test/order_search_test.dart
```

The scenarios above specify tests to implement. A completed Perch source check below is separate from running these application integration tests.

## Introduce the specific agent regression

In a throwaway copy, replace this source span:

```dart
if (!mounted || requestGeneration != generation) return;
```

with:

```dart
if (!mounted) return;
```

Run the relevant negative test and the Perch command on that broken copy. Restore the corrected source before committing the application. The supplied mutation reproduces the exact regression for the rule check.

## Preserve the requirement as a Perch rule

Save this in `.perch/rules/perch-guide-flutter-generation-safe-search.yaml` at the repository root, keeping your existing `perch.yaml`:

```yaml
- name: search-generation-current
  where: "lib/order_search.dart"
  ensure: >-
    In load, both the successful response and the caught-error path return before setState when requestGeneration differs from generation. Each completion path checks requestGeneration != generation together with !mounted. Checking only mounted permits an older request to overwrite the current state.
```

Install and authenticate the CLI once, then check the current working file:

```sh
npm install -g @lakeday/perch
perch login
perch check lib/order_search.dart --rules search-generation-current --json
```

Use Node 22 or newer. The framework can use another language; Perch’s CLI remains a Node command. A gated finding exits 3. Exits 1 or 2 mean the check did not complete and must be reported as a blocker.

## Inspect the captured rule check

On 2026-10-14, Perch using jev-latest checked the exact fixed and broken source provided here. The capture records SHA-256 hashes of both sources and the requirement.

| Source control | Exit | Outcome |
| --- | --- | --- |
| Broken | 3 | Rule finding |
| Corrected | 0 | No rule finding |

The rule distinguished these controls in this run. [Raw Perch capture](/generation-safe-search/capture.json) · [Exact sources and mutation](/generation-safe-search/source.json).

## Install the rule pack and configure your agent

[Download this rule pack ZIP](/generation-safe-search/rule-pack.zip) · [Download the YAML rules](/generation-safe-search/rules.yaml) · [Agent task](/generation-safe-search/agent-task.txt). The pack contains the rule, its example paths and the repair/recheck instructions. Review the `where` selector before using it in an existing project. Keep your root `perch.yaml`; install this rule as a separate file under `.perch/rules/`.

1. Install Perch using Node 22 or newer and sign in once:

```sh
npm install -g @lakeday/perch
perch login
```

2. Download the pack, inspect it, and extract it from your repository root. The extraction preserves any existing files:

```sh
curl -fL 'https://reporules.fyi/flutter/generation-safe-search/rule-pack.zip' -o 'perch-guide-flutter-generation-safe-search.zip'
unzip -n 'perch-guide-flutter-generation-safe-search.zip'
```

The installed rule is `.perch/rules/perch-guide-flutter-generation-safe-search.yaml`. Its selector matches `lib/order_search.dart` in this example; adapt the selector to your application file before checking an existing project.

3. Configure the coding agent you use. Run one of these commands:

Claude Code:

```sh
perch setup claude-code
```

Codex:

```sh
perch setup codex
```

Cursor:

```sh
perch setup cursor
```

Pi:

```sh
perch setup pi
```

4. Ask the agent to edit the implementation and check the saved requirement:

> Use the installed Perch skill while editing lib/order_search.dart. Preserve search-generation-current. Run perch check lib/order_search.dart --rules search-generation-current --json after the edit. Read each finding and the affected code, fix the implementation, and run the identical check again after the fix. Keep the rule and regression tests intact. Run the application's relevant regression tests and report the commands and actual results. Exit 3 means a rule finding; exit 1 or 2 means the check did not complete. Report an unavailable or incomplete check as blocked. Do not claim the application tests ran if only the Perch check ran.

5. After repairing a finding, run the same check again and inspect the result:

```sh
perch check lib/order_search.dart --rules search-generation-current --json
```

Commit the downloaded rule and the installed agent configuration with your application. The rule file adds no guarantee of correctness; keep the regression tests from this guide.

With the base reference fetched, use `perch scan --since origin/main --filter type=lint` in CI.

## Framework references and verification scope

- [api.flutter.dev reference](https://api.flutter.dev/flutter/widgets/State/setState.html)

The dated capture records the source check shown above. Implement the adapters, schema and regression tests described in this guide in your application. Unchanged requests reuse cached answers; fresh model judgments can vary. Model analysis sends relevant source to the configured service.
