Flutter and Dart gotchas (collections, widgets, theming)
flutterdartmaterial3riverpodthemingbugs
Small Dart and Flutter traps that produced real bugs in Forge (a Material 3 Flutter app) and Spacebar (a Flutter/Flame game). Flame-specific ones are in Flame engine architecture and gotchas.
Collections
- Never
firstWhere(test, orElse: () => list.first). When nothing matches it silently returns (and then mutates) the wrong item, and on an empty list it throwsStateError. UseindexWhere(test)and return early on -1. value.clamp(0, list.length - 1)throwsArgumentErroron an empty list because the lower bound exceeds the upper. CheckisEmptyfirst (seen in a command palette's arrow-key handler with no results).- When parsing JSON, guard nested maps with
is Mapconsistently (json['meta'] is Map ? ... : {}); a single unguarded cast throwsTypeErroron unexpected payloads.
Hashing and determinism
Object.hashis randomized per run. Do not seed anything persistent with it (a procedural world reshuffled on every launch). Use a fixed algorithm and pin it with tests; check VM and JS parity (Deterministic seeds for procedural worlds).
Widgets and theming
DropdownButtonFormFieldtakesinitialValue;valueis deprecated as of Flutter 3.41.- When bulk-replacing hardcoded colors with
theme.colorScheme.primary, somebuild()methods have nothemelocal; useTheme.of(context).colorScheme.primarythere. - Derive palette variants instead of hardcoding: chat bubble backgrounds and login gradients computed
from the seed color through
HSLColorkeep every palette consistent; a smallColorextension (.muted,.subtle,.faint) centralizes alpha levels. - Shimmer skeletons in place of spinners make list and detail loads feel faster.
- A keyboard command palette: wire Ctrl/Cmd+K in the app shell with
ShortcutsandActions, debounce the search, support arrow keys and Enter. - Give HTTP calls a timeout (Forge used 15 s); without one, pull-to-refresh can hang forever.
- Optimistic UI updates need a rollback path when the request fails.
From TLDR (Material 3 app, web + Android)
- Dart
replaceAlldoes not expand$1.s.replaceAll(re, r'$1')inserts the literal text$1(post excerpts read!$1). UsereplaceAllMapped(re, (m) => m[1]!). A private copy of the same buggy helper lived in a second screen; delete duplicates when fixing. - PHP JSON often sends numbers as strings (
"0").json['x'] as int?then throws or fails silently and the whole screen does not render. Parse defensively:int.tryParse('${json['x']}'). - M3
SnackBarwith an action ignoresdurationand stays until the user interacts. Show it with a very long duration and dismiss it yourself after N seconds (TLDR'sshowTimedSnackBar()). CallclearSnackBars()before showing a new one or repeated taps queue a pile of them. SelectableTextwins the long-press gesture over a parentGestureDetector.onLongPress. Put the parent's actions (Delete, Debug) into the selection toolbar viacontextMenuBuilderextraContextMenuButtonItems, and keep the parent long-press for the padding.- Selection highlight invisible on primary-colored bubbles: the default
selectionColorisprimaryat 40% opacity. Wrap the text in aTextSelectionThemederived from the text's own color (selectionColor: color.withAlpha(90),selectionHandleColor: color); text color always contrasts with its background. - Link colors on colored bubbles: a themed link color was unreadable on the primary bubble; inherit the text color and underline instead.
- Linkify regexes: use a lookbehind like
(?<![@\w.-])so emails and version strings (v1.52.0) are not turned into links; trim trailing punctuation and keep a closing)only when it balances one inside the URL. NavigationRail.trailinggets unbounded width; pin it withSizedBox(width: extended ? 256 : 56)and setminExtendedWidth: 256. Matching custom rail items to M3's extended destinations: 56 px min width, 8 px horizontal destination padding, labels inlabelMedium.- Widget tests: the default test surface is 800 px wide, so phone layouts are not exercised;
set
tester.view.physicalSizeto a phone width.AnimatedSwitcherkeeps the old child during its crossfade; pump past the duration before asserting it is gone. - Transient content in a chip makes it jump. A status suffix added with
if (suffix != null) Text(...)vanishes in one frame and the chip snaps narrower. Put it in anAnimatedSwitcherwhosetransitionBuildercombines a horizontalSizeTransitionwith aFadeTransition(left-alignedStackinlayoutBuilder), so the outgoing text collapses smoothly; drive the border/glow with anAnimatedContaineron the same curve and duration, and keep theBoxShadowin the list with alpha 0 when idle so it fades instead of disappearing (TLDR's AI health chip, post #1865). - Dispose
TextEditingControllers created for dialogs (showDialog(...).then((_) => c.dispose())). - Hoist
DateFormatinstances to static fields and readMediaQuery.sizeOf(context)once per build, not per list item. - Set
cacheWidth(display width x devicePixelRatio) on inline images so full-resolution photos are not decoded for thumbnails; keep full resolution in the zoom viewer. - Tooltips: a global
TooltipThemeData(waitDuration: 800ms)stops them flashing on every hover; keep them on icon-only buttons, drop them where the label is visible. - CustomPaint animated icons (TLDR's nav bar): wrap each in a
RepaintBoundary, setisComplex/willChangehints, start animating ~500 ms after the page transition, and show a static painted version when inactive (smoother than swapping to a Material icon). Offer a setting to turn them off.
Dart compiled to JavaScript (Flutter web)
- Integers are JavaScript numbers on the web.
Random().nextInt(1 << 32)isnextInt(0)there (the shift wraps to 0), which throws; Spectre's web demo was a blank page from v0.5.0 until it was found. Keep bit tricks under 2^31, or use two smaller draws. Rule adopted: open the built web demo in a browser before every release.
From Run (Flutter/Flame game)
- Dart package name is not the Android application id. Run's package is
run_game(import 'package:run_game/...'in tests) while the Android id iscom.justingolden.speedrun_platformer. - pubspec
assets:does not recurse. List every subdirectory (assets/audio/music/menu/, ...) or files in it are missing at runtime. - A getter that builds data runs on every access.
List<Theme> get builtinThemes => [...]rebuilt 134 pixel grids each time it was read, inside loops. Use a lazyfinal(and treat it as read-only). - Don't dispose
TextEditingControllers in a dialog's.then(): it crashed on hot restart. Own controllers in a StatefulWidget and dispose them indispose(). - No
setStateduring build: a callback that runs while building (Run's auto score submit) must use plain field assignment. - Don't compare float positions with
==(checkpoint identity drifted); use ids. - Cancel async work you might restart:
Future.delayedcannot be canceled; a death-respawn delay raced with level restarts until it became a cancellableTimer(and later game-time countdowns, see Fixed-timestep game loop for browser games). - Corrupt local data before
runApp(hard casts on stored JSON) gives a blank screen; decode defensively (Game content data models (stable ids, schemas, serialization)).
Tooling
flutter analyzeexits 1 on info-level lints; CI gates usually want--no-fatal-infos.flutter testpiped through another command loses its exit code; read the output.- Keep
lib/version.dartandpubspec.yamlversions in sync and bump before each commit; the+buildnumber is the Android versionCode.
State management
- With Riverpod and Flame together, provider writes during the game loop must be deferred with
addPostFrameCallback(Flame engine architecture and gotchas).
See also
- Flame engine architecture and gotchas
- go_router navigation patterns and opening your own links in-app
- A self-building app pipeline (Forge builds Forge)
Linked from
- Adversarial review before architecture decisions
- Flutter app architecture, state management and packages (2026 survey)
- flutter_quill rich-text editor gotchas (markdown, IME, spell check, fonts)
- Rendering markdown in Flutter (selection, code-block builders, tappable task lists)
- Testing Flutter/Flame games and running them in GitLab CI
- Wardriving on Android (Wi-Fi and cell logging with GPS)
- Zero layout shift for network images in Flutter (dimensions in the URL)