When to Use
Use this skill when:
- Defining or refactoring a theme, design tokens, or a color scale
- Extracting reusable widgets from a large screen
- Fixing a
RenderFlex overflowedorRenderViewport does not support returning intrinsic dimensions - Writing widget tests that assert layout, theme, or accessibility
- Auditing a UI for hardcoded values
- Removing an
AppBar, or building anything that touches the notch or the system bars - Counting how many rows a
Wraptakes, or fighting a constraint you thought you controlled - Diagnosing a test that passes alone and fails in the suite
- Reading a sibling app for patterns to reuse
Every rule below was learned by hitting it in a real app. The numbers are measured, not estimated.
Critical Patterns
1. Tokens go in a ThemeExtension, never in global constants
A global constant cannot depend on the active theme. That is the whole point: an app with several
themes and 144 hardcoded Colors.green/Colors.red has colors that do not change even in dark mode.
Tokens inside ThemeData also join the interpolation Flutter runs when the theme changes.
2. Split the tokens: the SCALE is fixed, only COLOR comes from the theme
spacing NO one scale, base 4
radius NO three values, not ten
typography NO six named roles
color YES from the active theme
A theme is a color decision. One theme having rounder cards than another is not a feature — it is what happens when ten different radii get written across fourteen files over months.
Consequence for lerp: return the scale unchanged and interpolate only color. Mid-animation a card
must not have radius 10, because nobody chose 10.
3. NEVER put ! on a theme-extension accessor
// WRONG — bit three times in one session
AppTokens get tokens => Theme.of(this).extension<AppTokens>()!;
// RIGHT — tokens are a PURE FUNCTION of the ColorScheme
AppTokens get tokens {
final tema = Theme.of(this);
return tema.extension<AppTokens>() ?? AppTokens.fromScheme(tema.colorScheme);
}
"Fail early if the app is misconfigured" sounds right and is false:
- Any tree mounted with a
ThemeDatathat is not the app's — a widget test, a preview, a harness — dies withNull check operator used on a null valuemid-build. That message says neither what is missing nor where. It is the opposite of failing well. - There is nothing to invent. The scale is fixed and the color derives from the scheme. What the theme publishes is a cache of that computation.
4. Semantic color is derived by CONTRAST, not by mode
Two fixed sets — one for light, one for dark — are still fixed. With hand-made palettes that fails the moment one has a surface with unusual brightness.
Start from a base hue per role and adjust its lightness until it reaches the contrast minimum against the theme's real surface.
Try BOTH directions. A luminance threshold (> 0.5 ? black : white) fails on mid-tones: over grey
#808080 (luminance 0.216) the threshold sends you toward white, which yields 3.95 and never reaches
4.5 — while black yields 5.3. A threshold cannot know which direction pays more.
Background tints go the other way: they must blend WITH the surface, not contrast against it. A disc background at 4.5 contrast is a stain, not a background.
5. Contrast ratio is BLIND to hue — never use it to test "distinguishable"
Green and red have nearly the same luminance: their contrast against each other is 1.01, as if they were the same color. Compare hue instead.
And the real lesson is upstream: meaning must never depend on color alone. A movement's sign gets
three signals — the arrow, the +/− on the amount, and the color. For someone who cannot tell those
two hues apart, the color says nothing.
6. Atoms are CLASSES, never Widget _buildX() methods
Flutter compares widgets by identity to decide what to rebuild. What a method returns has no stable identity, so it re-runs on every parent rebuild — and the parent is a 1600-line screen.
This has a name in the ecosystem's linters (avoid-returning-widgets) and Flutter's own performance
docs say the same.
7. Variants by PRESENCE, not by boolean flags
MovementCard(onDelete: ...) // this list deletes
MovementCard() // this one does not
A nullable callback beats showDelete: false — there is no flag to remember, and a widget that cannot
act does not draw a dead button.
8. An empty label renders NOTHING
Text('') is invisible but present in the tree. It silently breaks contracts like "with no
attachments, no number is shown".
9. "Loading" and "empty" are DIFFERENT states
// WRONG — with no items of the active kind, this spins FOREVER
if (items.isEmpty) return const CircularProgressIndicator();
Three states, not two: loading, empty, has-items. Conflating the first two produces a control that spins forever and reads to the user as "the control disappeared" — which is exactly how it gets reported.
The empty state must also SAY it is empty. "No hay categorías" is information; a spinner is a lie.
10. A label that is not a VALUE costs width for nothing
A chip or button label should show what is SELECTED, not what the control is called.
"Cuenta" the control's name -> the user already knows; costs 94px to say nothing
"Principal" the selected value -> earns its width
And if the value already lives elsewhere on screen, the control needs no label at all — just its icon. Measured consequence of getting this wrong: two name-only labels pushed a six-chip row from two rows to four.
11. Build late is NOT the same as load late
When screens fetch their own data in initState, an IndexedStack that builds all children fires
every fetch at startup — because IndexedStack builds ALL of them, it only shows one.
// The lever is not "load lazily", it is "BUILD lazily"
visited.contains(i) ? realScreen(i) : const SizedBox.shrink()
An unvisited tab has no initState to run, so it queries nothing. Once visited it stays mounted, so
state survives. Copying a nav-shell pattern from an app whose controllers live OUTSIDE the tree gives
a shell that loads everything at startup and looks correct.
Who Decides The Size — And It Is Not You
Four lessons that share one root: you do not control the constraints you think you control. Every one of these cost a failed derivation before it was measured.
The available width is MEASURED, never calculated
Do not derive it from the screen. Three derivations in a row were wrong:
"320 screen - 32 panel padding = 288 available" -> measured: 248
The widget was nested deeper than the calculation assumed. Print the parent's width in a test and read it. Any dimension you did not measure is a guess, and a guess that looks like arithmetic is worse than one that looks like a guess.
ConstrainedBox cannot narrow a TIGHT parent
// Parent is SizedBox(width: 320) -> TIGHT. This maxWidth is IGNORED; the child measures 320.
ConstrainedBox(constraints: BoxConstraints(maxWidth: 88), child: ...)
ConstrainedBox can only tighten within what the parent allows. Under a tight parent it does
nothing. Under a Wrap — which passes LOOSE constraints — it works.
This bites hardest in tests: a harness that wraps the widget in a fixed-width SizedBox
measures a situation that does not exist in production. Reproduce the real parent.
InputDecorator gives its child UNBOUNDED width
// Throws: RenderFlex children have non-zero flex but incoming
// width constraints are unbounded
InputDecorator(decoration: ..., child: Row(children: [Expanded(child: Text(name))]))
Nothing with flex can live inside an InputDecorator. And without flex, TextOverflow.ellipsis
does not clip either — so a long value overflows.
What works: a SINGLE non-flex child (it does receive a bounded width), with the ornaments in
prefixIcon/suffixIcon where InputDecoration expects them. For a tap-to-pick field, a
readOnly: true TextField clips by design.
A Wrap packs GREEDILY, so ORDER changes the row count
Two wide children separated by a narrow one cannot be joined:
order A: wide(112) narrow(44) wide(112) -> 3 rows (112+44 fits, +112 does not)
order B: wide(112) wide(112) narrow(44) -> 2 rows
Same children, same widths, different number of rows. If you are counting rows, the order is part of
the layout — not just a semantic choice. And three pixels can decide a row: reducing spacing from
8 to 4 was the difference once.
The Layout Traps
TextOverflow.ellipsis does NOTHING without a width constraint
// WRONG — the Text gets infinite width, never clips, OVERFLOWS
Row(children: [Text(long, overflow: TextOverflow.ellipsis), Icon(...)])
// RIGHT
Row(children: [Flexible(child: Text(long, overflow: TextOverflow.ellipsis, maxLines: 1)), Icon(...)])
The declared clip is decoration until something bounds the width. Audit for this pattern first — it
is the single most common cause of RenderFlex overflowed.
EVERY Row containing text needs that text flexible
Even a nine-character constant label. At 2× system text scale a PENDIENTE row asked for 2.7px more
than it had.
Data rows go in a Wrap, not in fixed-flex Rows
Row with Flexible(flex: 3/4/3) and spaceBetween overflows on a narrow screen. A Wrap drops to a
new line. Measured: 281px of overflow became zero.
Column defaults to MainAxisSize.max
Inside a bottom sheet opened with isScrollControlled: true that stretches the sheet to the full
screen height to show two thumbnails. Measured: 2368pt tall in a 2400pt canvas → 180pt with
MainAxisSize.min.
A ListView cannot answer intrinsic-dimension queries
An IntrinsicHeight (or any intrinsic-measuring) ancestor plus a ListView gives
RenderViewport does not support returning intrinsic dimensions. shrinkWrap does not fix it.
Escaping it means replacing SingleChildScrollView + IntrinsicHeight with a CustomScrollView and
slivers — a restructure, not an edit. Budget for it.
Tap targets: 44px minimum, and never adjacent to a destructive one
IconButton(padding: EdgeInsets.zero, constraints: const BoxConstraints()) is below the minimum. If
that button deletes something, a mis-tap is not recoverable — put other controls far from it, and assert
the distance in a test so the reason cannot be lost with the widget.
toStringAsFixed returns exponential notation at ≥ 1e21
You cannot build a long number string by making the number huge: 1e300.toStringAsFixed(2) is
"1e+300", six characters. The longest digit string the API produces comes from 1e20 — 24 characters.
The minus sign is − (U+2212), not -
If the UI writes the typographic minus — and it should, the hyphen is shorter and does not align with
tabular figures — then find.textContaining('-') finds nothing. Different characters.
System Chrome: What Nobody Handles For You
The moment a screen has no AppBar, two things that Flutter was handling become yours.
SafeArea moves the BACKGROUND too
On a colored band that must reach the screen edge, SafeArea is wrong: it insets everything, so the
notch area shows the scaffold surface instead of your color — a stripe of a different color above the
band, worse than the problem you set out to fix.
// The background fills; only the CONTENT is inset.
ColoredBox(
color: esquema.primary,
child: Padding(
padding: EdgeInsets.only(top: MediaQuery.paddingOf(context).top),
child: contenido,
),
)
With zero reserved — an Android without a notch — it adds nothing, which is what you want.
SystemUiOverlayStyle.light names the ICONS, not the background
AppBar picked this from its own background brightness. Without one, nobody declares it and the
status-bar icons can end up dark on a dark background: invisible.
// Dark background -> LIGHT icons. And estimate from the ACTUAL background color:
// there are light themes with a dark primary.
ThemeData.estimateBrightnessForColor(esquema.primary) == Brightness.dark
? SystemUiOverlayStyle.light
: SystemUiOverlayStyle.dark
This has no automated test: the status bar is not in the widget tree. Declare it, then look at it on a device. Say in the report that it was not covered.
Testing It
The harness must mount with the REAL app theme
A bare ThemeData(useMaterial3: true) in a test harness is a fidelity gap: the screen tests never
exercise the real theme. Nobody notices while screens hardcode their own colors; the day they read
tokens, every screen test dies at once.
MediaQuery must be copyWith from ambient, never constructed fresh
// WRONG — size becomes zero; a screen computing
// `size.height - kToolbarHeight` gets -56 and an invalid BoxConstraints
MediaQuery(data: MediaQueryData(textScaler: TextScaler.linear(2)), child: screen)
// RIGHT
Builder(builder: (context) => MediaQuery(
data: MediaQuery.of(context).copyWith(textScaler: TextScaler.linear(2)),
child: screen,
))
Two clocks, in this order: REAL first, SIMULATED second
Database work needs real time (its future never completes under the fake clock). Animations need the
fake clock to advance, and a zero-duration pump() does not advance it.
await tester.tap(find.byKey(k));
await tester.runAsync(() => Future.delayed(const Duration(milliseconds: 400))); // DB
await tester.pump(const Duration(milliseconds: 400)); // animation
MaterialApp interpolates theme changes. Reading a color right after swapping the theme returns the
OLD one — correctly: at t=0, lerp returns the starting value. A test that concludes "the color did not
change" is really proving the interpolation works.
Wait on the TREE, not on the view model
A view model usually mutates state and notifies listeners afterwards. Waiting on its state exits one step before the screen repaints, and the next assertion looks for something not yet drawn.
Verify a layout test BITES
Undo the fix, confirm it fails with the right reason, restore. A layout test never checked in reverse guards nothing.
Use hostile data
Long account names, the longest amount the API can render, 320px width, 2× text scale. Text that always fits proves nothing about clipping. But keep the rest normal: an absurd account name drags in a different defect and the test measures the wrong thing.
Do not add goldens while the design is still moving
A golden freezes appearance. Freezing it mid-iteration produces a test regenerated out of habit — and a test regenerated out of habit is not a test. Assert the contract instead: nothing overflows, the scale is one, the theme governs color.
DRAIN fire-and-forget work, or you break OTHER test files
A view model that starts un-awaited work — loadX(type) from a setter, a config write — finishes
after teardown closes the database:
A UserDashboardViewModel was used after being disposed
This database has already been closed
MissingPluginException(No implementation found for getApplicationDocumentsDirectory)
Two consequences, and the second is the nasty one:
- The test passes ALONE and fails in the full suite. That is the worst failure mode: people learn to re-run it instead of believing it.
- A heavy test file makes OTHER files flaky. Every harness mount costs a temp database and a dozen view models; with the CPU shared, condition-waits in unrelated files time out.
Fix both ends: drain before the test ends (await tester.asentar(300)), and MERGE tests that share
identical setup — with a distinct reason per assertion so a failure still says which contract
broke.
IndexedStack hides inactive children with Offstage
Finders skip offstage widgets by default, so an inactive tab "disappears":
expect(find.text('tab-0'), findsNothing); // offstage
expect(find.text('tab-0', skipOffstage: false), findsOneWidget); // still ALIVE
Both halves together are the proof that state was preserved rather than destroyed. And measure
initState calls, not widget constructions: a StatefulWidget is re-instantiated on every parent
rebuild — that is normal — and Flutter REUSES its State. Counting constructions reports a rebuild
loop that is not there.
Don't chain three route transitions in one test
Sheet → dialog → close → close under a mixed clock hangs. Split it: test the contract of the piece
(did anything change?) and the consumer's reaction separately.
Borrowing From A Reference App
A sibling app is worth reading, and worth reading CRITICALLY. What transfers and what does not:
Worth stealing
| Pattern | Why |
|---|---|
IndexedStack shell + per-tab lazy load | preserves filters, scroll and half-typed drafts |
| Icon + ALWAYS-visible label in nav | no destination is guessed from its icon |
| Pulsing skeleton instead of a spinner | shows the SHAPE of what is coming |
| Outline instead of shadow | a shadow needs re-tuning per mode; outlineVariant does not |
Do NOT copy, even when it looks harmless
| Anti-pattern | Why it is wrong |
|---|---|
ThemeData passed by constructor | the widget already has context; breaks theme rebuilds and isolated tests |
withAlpha(15), (40), (140), (230)... | opacity magic numbers, no scale, no name |
enum {warning, success} + isWarning ? a : b ×6 | a boolean in disguise; adding a third case touches six ternaries |
| A radius declared in the theme and re-written by hand | the theme said 12 and the screens wrote 8 sixty-seven times |
A placeholder that shipped (Text('L. 0.00')) | the price of not wiring the data from the start |
And know when the reference is EXHAUSTED. Once your design system has tested atoms the sibling app does not, keep reading it for architecture and stop reading it for widgets. Check whether it even has the thing you are about to copy: an app with no charts teaches nothing about charts.
Decision Tree
| Symptom | Cause | Fix |
|---|---|---|
RenderFlex overflowed by N pixels | Text in a Row with no width bound | wrap in Flexible/Expanded |
| Overflow only at 2× text scale | a Row whose label cannot shrink | Flexible + maxLines: 1 |
| Overflow only on narrow screens | fixed-flex data row | Wrap |
RenderViewport does not support returning intrinsic dimensions | ListView under an intrinsic-measuring ancestor | CustomScrollView + slivers |
| Bottom sheet fills the screen | Column is MainAxisSize.max | MainAxisSize.min |
Null check operator used on a null value in a build | ! on a theme extension | derive as fallback |
| Color identical in light and dark | hardcoded Colors.x | semantic token from the theme |
| Semantic color unreadable on some theme | fixed color, or single-direction contrast adjust | derive by contrast, try both directions |
| All screen tests die at once | harness mounts a bare ThemeData | mount AppTheme.lightTheme |
RenderFlex ... incoming width constraints are unbounded | flex child inside an InputDecorator | single non-flex child; ornaments in prefixIcon/suffixIcon |
maxWidth on a ConstrainedBox ignored | parent passes TIGHT constraints | reproduce the real (loose) parent; in tests, a Wrap |
More Wrap rows than the arithmetic predicts | greedy packing + wide/narrow order, or unmeasured available width | reorder, and MEASURE the parent width |
setState() or markNeedsBuild() called during build | writing a TextEditingController inside build | return a value from the sheet; let the form write its own state |
| A control spins forever | isEmpty treated as "loading" | three states: loading, empty, has-items |
Content under the notch after removing the AppBar | nobody descounts the top inset now | inset the CONTENT, let the background fill |
| Status-bar icons invisible | no AppBar to declare the overlay style | AnnotatedRegion<SystemUiOverlayStyle>, brightness from the real background |
| Test passes alone, fails in the suite | un-awaited work outliving teardown, or CPU contention | drain before ending; merge tests with identical setup |
| An inactive tab's widget "disappeared" | IndexedStack wraps it in Offstage | skipOffstage: false — and both halves are the assertion |
Audit Commands
Run these BEFORE proposing a redesign. Measure, don't estimate.
# Screens vs reusable widgets — an 8:1 ratio means there is no design system
wc -l lib/**/views/screens/*.dart | tail -1
wc -l lib/**/views/widgets/*.dart | tail -1
# Distinct radii (a system has 2-3) and font sizes (6-8 named roles)
grep -rhoE "BorderRadius\.circular\([0-9.]+\)" lib | sort | uniq -c | sort -rn
grep -rhoE "fontSize: [0-9.]+" lib | sort | uniq -c | sort -rn
# Hardcoded colors vs theme references
grep -rhoE "Colors\.[a-zA-Z]+|Color\(0x[0-9a-fA-F]+\)" lib | wc -l
grep -rhoE "theme\.colorScheme\.[a-zA-Z]+" lib | wc -l
# The anti-pattern: methods returning widgets
grep -rcE "^\s+Widget _[a-zA-Z]+\(" lib/**/views/screens/*.dart | grep -v ":0"
# Text with a declared clip and no width bound — the overflow generator
grep -rn -B 2 "TextOverflow.ellipsis" lib | grep -c "Flexible\|Expanded"
Then re-run them after, and report the numbers that moved. "We removed the hardcoded colors" is the kind of claim that gets believed instead of checked.
Honesty Rules
These are about how to REPORT the work, and they are part of the craft:
- A count is either zero or it is explained. Brand colors (a PDF's red, an Excel green) are legitimately hardcoded — they must look the same in both themes. Say that instead of rounding to zero.
- Extracting a piece used once is fine — say the real reason (it was the row that overflowed; it can be tested alone), not a fake one (reuse).
- When a task's claim turns out too generous, correct it. "The screen uses the tokens" is false if its biggest block still has ten hardcoded radii — and the user will notice by opening the app.
- Name what you did NOT deliver. A behavioral change that got reverted, a screen left out of scope, an approved mockup element still missing: the user finds these out anyway, and better from you.
Resources
- Reference implementation:
<ruta-del-proyecto>/lib/core/theme/app_tokens.dart— tokens, contrast derivation, and the corrections documented in place. - Atoms:
<ruta-del-proyecto>/lib/features/wallet/views/widgets/- variant-by-presence and hostile-data clipping:
balance_chip.dart,data_chip.dart,form_chip.dart,movement_card.dart - sheets that return a value instead of writing state:
picker_sheet.dart(with optional header),note_sheet.dart,accounts_sheet.dart,attachment_source_sheet.dart - two signals, never colour alone:
wallet_bottom_nav.dart,initial_avatar.dart - background to the edge, content inset:
balance_band.dart
- variant-by-presence and hostile-data clipping:
- Tests:
test/tokens_de_diseno_test.dart(scale vs colour),test/atomos_de_diseno_test.dart(atoms under hostile widths),test/pantallas_estrechas_test.dart(320px and 2× text scale),test/pastillas_del_formulario_test.dart(a chip with no value is NARROWER — the contract that makes six of them fit),test/alto_de_inicio_test.dart(measures the vertical budget and the notch inset, with the before/after numbers written into the file).