agentleFS
mikezamayiasmikezamayias/agent-skills/skills/flutter-async-cubit-safety/SKILL.md

flutter-async-cubit-safety

Skill1 starsChanged 27 days agoBSD-3-ClauseView on GitHub

Prevents "emit after close" crashes in Flutter BlocCubit by adding isClosed guards after every await. Use when writing async cubit methods, fixing Sentry StateError crashes, or reviewing cubit lifecycle safety.

The file

We split this skill into the rules it gives an agent

7 rules. About 0 are common, 3 are distinctive, and 4 are very specific to this project.

  • ≈0

    Common · estimate

    Many files like this have a rule of this kind.

  • ≈3

    Distinctive · estimate

    This author's own choices. Worth a look.

  • 4

    Very specific

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

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

    When a Cubit has async methods with multiple await calls, the cubit can be disposed (closed) while an async operation is in flight.

    line 16
  2. Very specific:

    Add if (isClosed) return; after every await in cubit methods:

    line 30
  3. Distinctive:

    Guard immediately after the await: - before any other logic

    line 52
  4. Very specific:

    After await cubit.save(), check context.mounted before Navigator.pop(context) or a SnackBar, because isClosed protects the cubit and not …

    line 56
  5. Very specific:

    If two methods can start the same search, they share one Timer?

    line 101
  6. Distinctive:

    When writing or reviewing async cubit methods:

    line 111
  7. Distinctive:

    Search for cubits missing guards:

    line 121

≈ “Common” is an estimate: at least 1 in 5 of the 350,495 skill 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
SKILL.md

Flutter Async Cubit Safety

Prevent StateError: Cannot emit new states after calling close crashes by guarding every emit() after an await.

The Problem

When a Cubit has async methods with multiple await calls, the cubit can be disposed (closed) while an async operation is in flight. The async continuation then runs and calls emit() on a closed cubit, causing:

StateError: Cannot emit new states after calling close

This is a top Sentry crash pattern in Flutter apps. It happens when:

  • User navigates away while data is loading
  • Widget tree rebuilds and old cubit is disposed
  • App goes to background during async operations

The Fix

Add if (isClosed) return; after every await in cubit methods:

Future<void> loadData() async {
  emit(const DataLoading());

  final result1 = await _service.fetchFirst();
  if (isClosed) return;  // Guard #1

  final result2 = await _service.fetchSecond(result1);
  if (isClosed) return;  // Guard #2

  final result3 = await _service.fetchThird(result2);
  if (isClosed) return;  // Guard #3

  emit(DataLoaded(data: result3));
}

Rules

  1. Every await needs a guard - even if the next line isn't emit(), because later code may depend on cubit being open
  2. Guard immediately after the await - before any other logic
  3. Use return, not throw - silently bail out, the cubit is already disposed
  4. Also guard refresh() methods - they typically call the load method internally
  5. The widget that awaits a cubit method needs its own guard. After await cubit.save(), check context.mounted before Navigator.pop(context) or a SnackBar, because isClosed protects the cubit and not the BuildContext.

Common Patterns

Sequential awaits

final profile = await _userService.fetchProfile();
if (isClosed) return;

final feed = await _feedService.fetchFeed(profile.id);
if (isClosed) return;

emit(Loaded(profile: profile, feed: feed));

Try-catch with awaits

try {
  final data = await _repo.fetch();
  if (isClosed) return;
  emit(Loaded(data));
} catch (e) {
  if (isClosed) return;  // Also guard in catch!
  emit(Error(e.toString()));
}

Refresh that calls load

Future<void> refresh() async {
  await _service.clearCache();
  if (isClosed) return;
  await loadData(force: true);
  // No guard needed here - loadData has its own guards
}

Debounced or overlapping searches

isClosed stops an emit after the cubit is disposed. It does not stop an older call from overwriting a newer one, because both calls run while the cubit is open.

  • If two methods can start the same search, they share one Timer? _debounce field, and every method that searches immediately calls _debounce?.cancel() first.
  • Give each awaited search a sequence number (final id = ++_seq;), and after the await return when id != _seq, so only the latest search emits.
  • Override close() to cancel the timer, then call super.close(). This stops a debounce that has not fired. A search already awaiting still needs the isClosed guard after its await (inference from the bloc source, where emit throws after close).
  • Emit the loading state when the search starts, not when the input changes, because the debounce window is waiting and nothing is loading yet. This rule rests on one author's report of a flicker, so treat it as a default for debounced search only.

Checklist

When writing or reviewing async cubit methods:

  • Identify every await in the method
  • Add if (isClosed) return; after each one
  • Check catch blocks for emits after awaits
  • Check refresh/retry methods that call load methods
  • Search for emit( and verify each has a guard if preceded by await

Detection

Search for cubits missing guards:

# Find async cubit methods
grep -rn "Future<void>.*async" lib/features/*/presentation/cubit/

# Find emits after awaits (manual review needed)
grep -rn "emit(" lib/features/*/presentation/cubit/ | grep -v "isClosed"

Sources

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.