/flutter:error-handling-typed-resultsfrom Flutter Skills
Enforces a typed-error spine with sealed Result<T,F> and per-boundary Failure types. Recoverable failures are values, only bugs throw. Includes convert-at-boundary logging, exhaustive switching, global error net wiring, and never-lose-data layer with transactions, autosave drafts, and soft-delete/Undo.
Ships in Flutter Skills. Installing the plugin adds it to Claude Code.
What the skill costs in Claude's context, stage by stage
Name and description: Claude knows it exists.
SKILL.md joins the conversation and stays.
Read when SKILL.md points to them; scripts run unread.
Recoverable failures are typed values that flow through the layers and are switched on exhaustively; only genuine bugs and unrecoverable states throw, and those are caught once by a global net. Wrapped around both, never-lose-data — transactions, autosave drafts, soft-delete/Undo — is a first-class subsystem, not plumbing. Two tiers, no middle ground.
Read the reference for the task at hand:
references/result-failure-spine.md — the Result/Failure source, the per-boundary taxonomy, convert-at-boundary, the global net, isolate re-wrapping, and local logging.references/mechanism-selection.md — throw vs assert vs Exception vs sealed outcome, @useResult, and the runZonedGuarded decision.references/never-lose-data.md — one transaction per mutation, debounced autosave drafts, optimistic soft-delete / Trash / Undo behind one filter.Run scripts/check-swallowed-catch.sh and scripts/check-softdelete-parity.sh before a PR.
Result<T, F extends Failure> (sealed Ok/Err). Throwing across a layer for an expected failure is a review reject.Result and Failure in a Flutter-free layer so pure logic and repositories share ONE vocabulary. result_dart is the sanctioned drop-in if you want ready-made flatMap/mapError/AsyncResult — adopt it wholesale or hand-roll; never mix both.Failure family per boundary, each subtype carrying a stable code + typed params — NEVER a user-facing or localized string. A baked-in message breaks translation, RTL mirroring, and numeral rendering. Localize from the code at the presentation edge.switch failures exhaustively with NO default: / case _:. Sealed exhaustiveness turns "added a new failure" into a compile error until every switch covers it; a default: silently defeats the only compiler-grade safety net you have.on clause, log the original error + stack to the local log BEFORE returning the typed failure. A PlatformException/SqliteException/FormatException never leaks past its adapter into a Notifier or widget.catch (_) {}, bare catch (e) that discards type/stack, and throw e (use rethrow) are banned — CI greps for them. Never catch Error subtypes (StateError, AssertionError): those are bugs, let them crash in debug.outOfRange variant, a clamped value). Programmer invariants use assert (stripped in release). Async/error handling lives outside pure code, at the boundary seam.Result values that never throw across a layer, so they never reach the net. The two handlers (FlutterError.onError + PlatformDispatcher.instance.onError) and their install order are owned by app-startup-and-bootstrap; this skill owns only the taxonomy of what reaches them. The runZonedGuarded-only-for-a-crash-SDK decision is in references/mechanism-selection.md.Isolate.run/compute errors as Result at the call site. Isolate errors do not hit FlutterError.onError; catch them where you await or they propagate opaquely.transaction(...) per multi-table mutation (all-or-nothing); persist in-progress form state to a debounced drafts table; delete via is_deleted soft-delete behind a single shared filter, with SnackBar Undo. Detail in references/never-lose-data.md.Native Dart 3 sealed, zero dependencies. Pure logic and repositories return the same type.
// lib/core/result.dart — Flutter-free.
sealed class Result<T, F extends Failure> {
const Result();
}
final class Ok<T, F extends Failure> extends Result<T, F> {
const Ok(this.value);
final T value;
}
final class Err<T, F extends Failure> extends Result<T, F> {
const Err(this.failure);
final F failure;
}
extension ResultX<T, F extends Failure> on Result<T, F> {
R fold<R>(R Function(T) onOk, R Function(F) onErr) => switch (this) {
Ok(:final value) => onOk(value),
Err(:final failure) => onErr(failure),
};
Result<R, F> map<R>(R Function(T) f) => switch (this) {
Ok(:final value) => Ok(f(value)),
Err(:final failure) => Err(failure),
};
}
// lib/core/failure.dart — one family per boundary; code + typed params, no strings.
sealed class Failure {
const Failure();
String get code; // stable, localization-key-like, e.g. 'db.not_found'
}
sealed class OrderFailure extends Failure {
const OrderFailure();
}
final class OrderNotFound extends OrderFailure {
const OrderNotFound(this.id);
final String id;
@override
String get code => 'order.not_found';
}
final class OrderConstraintViolated extends OrderFailure {
const OrderConstraintViolated(this.field);
final String field;
@override
String get code => 'order.constraint_violated';
}
final class OrderStoreUnavailable extends OrderFailure {
const OrderStoreUnavailable();
@override
String get code => 'order.store_unavailable';
}
Sealed variants are final class + const ctor + final fields. You switch on the type; you never compare instances, so do not write ==/hashCode or reach for freezed/equatable here.
Wrap the dangerous call once. Log the original exception + stack before returning a typed, string-free failure. @useResult makes discarding the outcome a lint error.
// lib/data/order_repository.dart — the ONLY place the store SDK is imported.
@useResult
Future<Result<Order, OrderFailure>> findOrder(String id) async {
try {
final row = await _dao.byId(id).timeout(const Duration(seconds: 5));
if (row == null) return Err(OrderNotFound(id));
return Ok(row.toDomain());
} on TimeoutException catch (e, st) {
_log.error('order.find.timeout', e, st); // log FIRST — never swallow
return const Err(OrderStoreUnavailable());
} on SqliteException catch (e, st) {
_log.error('order.find.db', e, st);
return Err(_mapDbException(e)); // typed, stable code, no strings
}
}
The Notifier (ViewModel) switches every case; localization happens here, from the code.
// lib/features/order/order_notifier.dart — manual Riverpod 3.x AsyncNotifier
// ViewModel. Hand-written providers are the default; `@riverpod` codegen is an
// optional alternative (see state-management-riverpod). `autoDispose`/`family`
// are provider MODIFIERS — never AutoDispose*/*Family base classes, which were
// removed in 3.0. The family arg (the order id) is read via `arg`.
final orderNotifierProvider =
AsyncNotifierProvider.autoDispose.family<OrderNotifier, Order, String>(
OrderNotifier.new);
class OrderNotifier extends AsyncNotifier<Order> {
@override
Future<Order> build() async {
switch (await ref.watch(orderRepositoryProvider).findOrder(arg)) {
case Ok(:final value):
return value;
case Err(:final failure): // sealed => no default:; adding a case is a compile error
throw OrderLoadException(failure); // surfaces as AsyncValue.error to the View
}
}
}
// A View renders AsyncValue loading/error/data; it maps failure.code to a localized string.
For UI that recovers per-case rather than showing a generic error, switch the failure in the widget and map each code to an l10n message — never a default:.
app-startup-and-bootstrap owns the net and everything about it: the two handlers — FlutterError.onError (build/layout/paint sync errors) and PlatformDispatcher.instance.onError (async + platform-channel errors) — installed before runApp, onError returning true, no runZonedGuarded, and ProviderException unwrapped before logging. Do not restate that bootstrap() here.
What this skill owns is the taxonomy of what reaches those handlers: only genuine bugs and unrecoverable states. Every recoverable failure is a typed Result/Failure value that never throws across a layer, so it never reaches the net. Isolate errors are the one thrown category the net misses — re-wrap them as Result at the call site (below).
// Heavy work runs off the UI isolate; its errors do NOT reach FlutterError.onError.
Future<Result<Report, ComputeFailure>> buildReport(ReportInput input) async {
try {
return Ok(await Isolate.run(() => ReportBuilder().run(input)));
} on Object catch (e, st) {
_log.error('report.compute', e, st);
return const Err(ComputeFailed('report'));
}
}
catch (_) {} / bare catch (e) — discards type and stack; fatal when the lost data can't be re-fetched. Catch narrowly and log (e, st).String inside a Failure/Exception — breaks translation, RTL mirroring, numeral rendering. Codes + typed params only.default: / case _: on a sealed switch — a new failure subtype slips through unhandled; you lose compile-time exhaustiveness.throw e; in a catch — resets the stack to the rethrow line. Use rethrow.PlatformException/SqliteException/FormatException reaching a Notifier or widget. Convert it at the adapter.throw inside pure logic for uncertainty — keep it total; return an explicit "cannot within budget" value.Error subtypes "to be safe" — you are hiding a bug; let it crash in debug.Result<T> whose error arm is Exception/Object — no type to switch on; every case gets silently dropped. Type the error as F extends Failure.assert on a platform/plugin return value — the assert is stripped in release, so the real-device failure becomes total silence. Return a typed failure instead.PlatformDispatcher.onError.Result<T, F>; every call site switches all cases with no default:.Failure; every subtype carries a stable code + typed params, zero localized strings.on clauses), log (e, st) FIRST, then return a typed Err; no bare/empty catch; rethrow preserves stacks.app-startup-and-bootstrap); no recoverable failure throws across a layer.Isolate.run/compute calls re-wrap errors as Result at the call site.scripts/check-swallowed-catch.sh and scripts/check-softdelete-parity.sh pass.async-safety for the arrow-callback Future-drop hole no lint catches, unawaited/.timeout/mounted discipline, and subscription/timer disposal.dart3-idioms-and-coding-standards for sealed classes, exhaustive switch expressions, and total non-throwing functions.state-management-riverpod for AsyncNotifier ViewModels, AsyncValue loading/error/data, and providers-as-DI.app-startup-and-bootstrap for main() ordering and where the global error handlers install.persistence-drift for the DAO/transaction machinery, run-migration for schema evolution.service-boundary-and-native for the injectable-interface seam where SDK/plugin exceptions are caught and converted.i18n-rtl-l10n for mapping a failure code to a localized message and for numeral normalize-before-parse (do not duplicate it here).testing-strategy for asserting on Err branches and fake_async clock-driven debounce/purge tests.lint-and-style-config for promoting avoid_catches_without_on_clauses, unawaited_futures, and unused_result to errors.ui-states-and-feedback for how a Failure code becomes an error state, a snackbar, or an Undo — never a rendered exception.data-export-and-restore for the user-facing end of never-lose-data: versioned backups and an all-or-nothing restore.rethrow, catch specificity)sealedIsolate.run, message passing)FlutterError.onError, PlatformDispatcher.instance.onError)@useResult)examples/soft_delete_undo.dart (opens in a new tab)examples/transactional_write.dart (opens in a new tab)examples/typed_result_boundary.dart (opens in a new tab)references/mechanism-selection.md (opens in a new tab)references/never-lose-data.md (opens in a new tab)references/result-failure-spine.md (opens in a new tab)scripts/check-softdelete-parity.sh (opens in a new tab)scripts/check-swallowed-catch.sh (opens in a new tab)What SKILL.md sets; muted values are Claude Code's defaults
40 skills in this plugin
/accessibility-as-codeEnforces accessibility as a correctness property authored into each widget — Semantics(button/label) or ExcludeSemantics on every node, a11y state read from MediaQuery not app state, never MediaQuery.withClampedTextScaling / textScaleFactor / FittedBox / TextOverflow.ellipsis to fit a label, non-color redundant channels (icon+label+shape+text) for every state, contrast against composited backgrounds (4.5:1 body / 3:1 large), 44px single-tap targets, OrdinalSortKey traversal, and honoring boldText / reduce-motion. Use when adding a GestureDetector/InkWell or any tap target, adding an Icon or Image, reaching for withClampedTextScaling/FittedBox/ellipsis/textScaleFactor to make text fit, encoding state via color, sizing type, ordering focus traversal, or reviewing any View for screen-reader/switch/low-vision support./adaptive-layoutEnforces adapting layout by available CONSTRAINTS/size, never device or platform checks — LayoutBuilder + MediaQuery.sizeOf/paddingOf/viewInsetsOf (not .of) for narrow rebuilds, Material 3 window size classes (compact <600, medium 600-840, expanded 840-1200, large >1200) as the breakpoint vocabulary, navigation affordance chosen by width (NavigationBar → NavigationRail → NavigationDrawer), list-detail single-pane-vs-two-pane, readable max-width via ConstrainedBox, Flexible/Expanded/FractionallySizedBox over fixed widths, SafeArea + display cutouts + keyboard insets, never lock orientation, foldable/hinge awareness via MediaQuery.displayFeatures, and golden-matrix verification across sizes. Use when building responsive or adaptive UI, tablet/desktop/foldable support, master-detail or two-pane screens, a NavigationRail-vs-BottomNav shell, breakpoints, LayoutBuilder, MediaQuery sizing, SafeArea/cutouts, or fixing overflow at large widths./ads-and-iap-monetizationEnforces opt-in, rewarded-first monetization over the service seam — a rewarded view grants exactly one benefit and only on a genuine reward outcome (a sealed Rewarded/Dismissed/NoFill), earn loops capped per day against an injected Clock, the earn control preloaded and hidden unless an ad is loaded so a fresh account never dead-ends on "no ads available" (a Guideline 2.1 risk), interstitials only at a natural break under a count-and-elapsed cap owned by the service so callers stay dumb, no banner on the primary work surface, one non-consumable unlock plus Restore re-checked each launch and committed through the single write path before the UI reacts, one derived isEntitled provider as the only gate, and the entitlement restored BEFORE the ad SDK initializes so a paying user never starts it, resolves consent, or sees a tracking prompt. Use when adding ads, wiring a rewarded earn loop, placing an interstitial, building a paywall, gating an entitlement, or setting up ad units./app-startup-and-bootstrapEnforces a fixed main() cold-launch order — crash-log sink + FlutterError.onError + PlatformDispatcher.onError installed BEFORE any code that can throw, settings/theme read before runApp so the first frame paints correct, real infra constructed in a composition-root bootstrap() and injected via ProviderScope overrideWithValue over throwing placeholder providers, non-blocking warm-up deferred to addPostFrameCallback, exactly two error handlers with NO runZonedGuarded, ProviderException unwrapped before logging, and a WidgetsBindingObserver that flushes durable state on background/resume. Use when editing lib/main.dart, main_<flavor>.dart, bootstrap.dart or app.dart, reordering anything in main(), adding a splash/onboarding/permission gate, restoring theme before first paint, wiring a DB or service into ProviderScope, handling app-lifecycle background/resume flushes, or chasing cold-start latency, ANRs, or first-frame jank./async-safetyEnforces 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./ci-pipeline-and-gatesEnforces a lean GitHub Actions Flutter CI where every gate maps to one named release-blocking contract — pinned runner + subosito/flutter-action@v2 toolchain, dart format --set-exit-if-changed, flutter analyze --fatal-infos, build_runner and drift schema freshness (git diff --exit-code), flutter test --test-randomize-ordering-seed random, static import/banned-string greps that catch what runtime can't, coverage-as-report-never-a-gate with the upward-lie fixed, verify-never-bless goldens (no --update-goldens in CI), and an honest statement of what CI cannot prove (audio, real fonts, on-device behaviour). Use when editing .github/workflows/*.yml, adding or removing a job or step, wiring a codegen/schema/format/analyze/coverage gate, writing a grep-based policy test or gate script under test/policy or tool/, pinning action versions, or claiming CI proves something it can't.npx claudepluginhub zakariaf/flutter-skills --plugin flutterOther plugins' skills for the same job