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.
In this repository52 other files it gives its agents.
- academic-research-assistantSkill
- answer-sheetSkill
- app-graphicsSkill
- app-landing-pageSkill
- app-screenshotsSkill
- break-uiSkill
- consumer-app-from-behaviorSkill
- cross-language-safetySkill
- dart-tool-scriptsSkill
- decision-sweepSkill
- engineering-diarySkill
- figma-review-loopSkill
- flutter-app-size-auditSkill
- flutter-async-at-the-edgeSkill
- flutter-bloc-clean-architectureSkill
- flutter-clean-architecture-tddSkill
- flutter-cubit-smart-cachingSkill
- flutter-error-logging-conventionsSkill
- flutter-observability-instrumentationSkill
- flutter-paywall-and-review-timingSkill
- flutter-precommit-cleanupSkill
- flutter-router-decisionSkill
- flutter-runtime-safetySkill
- flutter-shorebird-otaSkill
- flutter-stream-architectureSkill
- flutter-strict-analysisSkill
- flutter-web-first-paintSkill
- forced-pivot-15-daySkill
- gplay-consoleSkill
- ios-distribution-feature-flagsSkill
- launch-readinessSkill
- launch-watchSkill
- locale-expert-reviewSkill
- market-pulseSkill
- mobile-ui-referenceSkill
- moscow-prioritizationSkill
- orchestrate-agentic-engineeringSkill
- parallel-agent-inboxSkill
- paywall-conversion-flowSkill
- paywall-transparencySkill
- proactive-crash-repair-loopSkill
- promise-auditSkill
- pr-preview-shippingSkill
- ship-first-dollar-appSkill
- slim-ios-simulator-fleetSkill
- spec-sql-harnessSkill
- store-launch-mastermindSkill
- sync-contextSkill
- task-blitzSkill
- techdebtSkill
- vendor-decisionSkill
- web-interface-reviewSkill
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
- Very specific: line 16
When a Cubit has async methods with multiple await calls, the cubit can be disposed (closed) while an async operation is in flight.
- Very specific: line 30
Add if (isClosed) return; after every await in cubit methods:
- Distinctive: line 52
Guard immediately after the await: - before any other logic
- Very specific: line 56
After await cubit.save(), check context.mounted before Navigator.pop(context) or a SnackBar, because isClosed protects the cubit and not …
- Very specific: line 101
If two methods can start the same search, they share one Timer?
- Distinctive: line 111
When writing or reviewing async cubit methods:
- Distinctive: line 121
Search for cubits missing guards:
≈ “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.
Files
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 closeThis 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
- Every
awaitneeds a guard - even if the next line isn'temit(), because later code may depend on cubit being open - Guard immediately after the await - before any other logic
- Use
return, notthrow- silently bail out, the cubit is already disposed - Also guard
refresh()methods - they typically call the load method internally - The widget that awaits a cubit method needs its own guard.
After
await cubit.save(), checkcontext.mountedbeforeNavigator.pop(context)or a SnackBar, becauseisClosedprotects the cubit and not theBuildContext.
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? _debouncefield, 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 whenid != _seq, so only the latest search emits. - Override
close()to cancel the timer, then callsuper.close(). This stops a debounce that has not fired. A search already awaiting still needs theisClosedguard after its await (inference from theblocsource, whereemitthrows 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
awaitin 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 byawait
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
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
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.

