async-safety
Enforces no-silent-failure async discipline in Flutter/Dart — the arrow-callback Future-drop hole no lint catches (`onTap: () => vm.save(x)`), void-returning event handlers, a mounted/ref.mounted guard after EVERY await before touching BuildContext, capturing Navigator/ScaffoldMessenger before the gap, honest `unawaited()` that always ends in catchError, no empty/bare catches, `rethrow` over `throw e`, and disposing every StreamSubscription/StreamController/Timer/sink. Use when writing or reviewing async/await, wiring onTap/onPressed/onSubmitted or any VoidCallback, touching BuildContext after an await, writing initState/dispose/addPostFrameCallback, adding a Timer or Future.delayed, writing a try/catch, or seeing use_build_context_synchronously, cancel_subscriptions, close_sinks, unawaited_futures, or discarded_futures.
zakariaf · 已有静态检查记录
安装与使用
运行命令前先阅读来源与依赖说明。复制命令不会自动安装或执行。
npx skills add zakariaf/Flutter-Skills --skill async-safety技能说明
name: async-safety
description: Enforces no-silent-failure async discipline in Flutter/Dart — the arrow-callback Future-drop hole no lint catches (onTap: () => vm.save(x)), void-returning event handlers, a mounted/ref.mounted guard after EVERY await before touching BuildContext, capturing Navigator/ScaffoldMessenger before the gap, honest unawaited() that always ends in catchError, no empty/bare catches, rethrow over throw e, and disposing every StreamSubscription/StreamController/Timer/sink. Use when writing or reviewing async/await, wiring onTap/onPressed/onSubmitted or any VoidCallback, touching BuildContext after an await, writing initState/dispose/addPostFrameCallback, adding a Timer or Future.delayed, writing a try/catch, or seeing use_build_context_synchronously, cancel_subscriptions, close_sinks, unawaited_futures, or discarded_futures.
Async safety: no failure may be silent
Async bugs are silence. A dropped Future swallows its error; a dead BuildContext throws into a void; a leaked subscription fires into a disposed widget. An app with no telemetry has exactly two feedback loops — the analyzer and the test suite — and the analyzer has one hole big enough to drive the product through. Close it structurally, not with discipline. This skill applies whenever you write async/await, wire a callback, or hold a subscription, timer, or sink.
Non-negotiable rules
- A callback must never touch a
Future. EveryonTap/onPressed/onSubmitted/VoidCallbackhandler returnsvoid.onTap: () => vm.save(x)wheresaveis async is caught by NO lint (see below) — the fix is shape, not vigilance. - A
mounted/ref.mountedguard goes after EVERY await, immediately before the nextBuildContextuse — never once at the top, never before the await where it proves nothing. Or capture the object you need before the gap. - Multiple awaits ⇒ the guard sits after the LAST one. A guard only certifies the interval since the most recent suspension point.
unawaited(x)is legal only ifxprovably cannot fail silently — it ends in a.catchError(...)or is total. Bareunawaited(f)routes errors toPlatformDispatcher.onError, detached from the UI. That is silence with a permission slip.- Every
StreamSubscription,StreamController,Timer, and sink is released indispose()/ref.onDispose. Prefer not owning it: a provider gives teardown for free. - Every timer/stream callback that calls
setStateguardsmountedfirst. ATimerholds a strong reference to its closure and fires happily after the widget is gone. - No empty catch, no bare catch, no swallow. Every
catchhas anonclause (except the crash logger's own write), logs with its stack, and surfaces the failure. Userethrow, neverthrow e— the latter resets the stack trace. - Never
asserta platform/plugin return value. Asserts are stripped in release: green in every test, absent on the device — the perfect silent-failure bug. - Nothing unbounded runs before
runApp. No migration, no plugin warm-up. Show a usable first frame, then warm up inaddPostFrameCallback, unawaited. - No
runZonedGuarded. Two error handlers suffice —app-startup-and-bootstrapowns installing them, their pre-runAppordering, thePlatformDispatcher.onErrorreturn truerule, and never letting a handler throw. Don't restate that machinery here.
The hole no lint catches
Verified with discarded_futures, unawaited_futures, and unused_result all at error:
| Callback shape | Diagnostics |
|---|---|
onTap: () => vm.save(note) | none — all three miss it |
onTap: () { vm.save(note); } | discarded_futures |
onTap: () async { vm.save(note); } | unawaited_futures |
onTap: () => vm.saveNote(note) (void method) | clean — the fix |
The arrow closure returns the Future, so every rule considers it used; the target type is VoidCallback, so Dart's void-compatibility discards it. The Future and its error both hit the floor. This is the most idiomatic way to wire a Flutter tap, and it is precisely where silence hides.
The mitigation is structural, never disciplinary: give the handler method a void return and do the unawaited(... .catchError(...)) inside it. A callback then never holds a Future, so the hole is unreachable by construction.
// A void-returning seam. Do NOT "improve" this to Future<void> — that
// reopens the arrow-callback hole. Keep this comment; without it the next
// reader tidies the void away.
void saveNote(Note note) {
unawaited(
_persist(note).catchError((Object e, StackTrace s) {
_log.record('save path threw: $e', s);
_showError('That note was not saved.');
}),
);
}
Future<void> _persist(Note note) async {
final result = await _repo.save(note); // returns a typed Result, does not throw
switch (result) {
case Ok():
return;
case Err(:final failure):
_log.record('save failed: ${failure.code}', StackTrace.current);
_showError('That note was not saved.');
}
}
The async gap and BuildContext
context is a live handle into the element tree, not a value. await yields to the event loop; while suspended the route may pop, the dialog may close, the State may be disposed. On resume the handle points at a corpse. use_build_context_synchronously is why — promote it to error.
// WRONG — the Element may be defunct after the gap.
Future<void> _save() async {
await _repo.save(note);
Navigator.of(context).pop();
}
Two legitimate fixes; prefer whichever makes intent obvious.
// RIGHT — capture before the gap. The captured object does not need the tree.
Future<void> _save() async {
final navigator = Navigator.of(context);
await _repo.save(note);
navigator.pop();
}
// RIGHT — guard after the gap, immediately before the context use.
Future<void> _save() async {
await _repo.save(note);
if (!mo
阅读完整来源 ↗