flutter-widget-architecture
Use when building Flutter screens - compose small stateless widgets, keep layout declarative, decide layout by available width not device/orientation, separate presentation from business logic, and use the theme not hardcoded styles
- License 许可
- Apache-2.0
- 最近更新
- 2026-11-15
- Stars
- ★ 122
- Forks
- 18
01 前言 Front Matter
- name
- flutter-widget-architecture
- source
- flutter/agent-plugins (BSD-3-Clause), adapted
- category
- architecture
- tech_stack
- Flutter
- description
- Use when building Flutter screens - compose small stateless widgets, keep layout declarative, decide layout by available width not device/orientation, separate presentation from business logic, and use the theme not hardcoded styles
03 SKILL.md 正文
Flutter Widget Architecture
Overview
Flutter UI is a tree of widgets. The quality difference is in decomposition: small, focused, mostly-stateless widgets that read like the UI they render, with business logic pushed out of the widget tree.
Core principle: Widgets describe what the UI looks like given state. They do not fetch data, hold business rules, or talk to the network — that lives in state/services (see flutter-state-management).
Rules
- Prefer
StatelessWidget. Reach forStatefulWidgetonly for truly local, ephemeral UI state (an animation controller, a text field's focus). App/business state lives in your state management layer. - Small widgets over deep
buildmethods. Abuildlonger than ~40 lines or nested 5+ deep is a set of extract-widget opportunities. Extract named widgets, notWidget _buildX()helper methods (named widgets get their own rebuild scope and are testable). constconstructors everywhere possible — aconstwidget subtree is skipped on rebuild. This is the cheapest performance win in Flutter.- Theme, not hardcoded styles. Colors, text styles, spacing come from
Theme.of(context)/ a design-token file (context.space, seemobile-design-system-foundation) — never scatteredColor(0xFF...)and magic paddings. This is the Flutter equivalent of "no custom CSS." - Keys only when you need identity across rebuilds (reorderable lists) — don't sprinkle them.
- Decide layout by available width, not device type or orientation. Use
LayoutBuilderorMediaQuery.sizeOf(context)— neverMediaQuery.of(context).size(that rebuilds on every metric change, not just size) and never a device-type/orientation check to pick a layout. Seeadaptive-layoutandmobile-visual-self-reviewfor the size matrix this must hold at. Color.withValues(alpha:), not the deprecatedwithOpacity(precision loss).TextScaler(MediaQuery.textScalerOf(context).scale(...)), not the deprecatedtextScaleFactor.
Worked Example
// ❌ one giant build, hardcoded style, logic in the widget
Widget build(BuildContext context) {
return Container(padding: EdgeInsets.all(16), color: Color(0xFF2196F3),
child: Column(children: [ Text(task.title, style: TextStyle(fontSize: 18)), /* 60 more lines */ ]));
}
// ✅ composed from small const widgets, themed, logic elsewhere
class TaskCard extends StatelessWidget {
const TaskCard({super.key, required this.task});
final Task task;
@override
Widget build(BuildContext context) => Card(
child: Padding(
padding: EdgeInsets.all(context.space.md), // token, not a magic 16
child: Column(children: [
TaskTitle(title: task.title), // extracted, testable atom
TaskStatusChip(status: task.status), // extracted molecule
]),
),
);
}
Layout-error catalogue
Four errors that show up repeatedly and what they mean:
- "Vertical viewport was given unbounded height" — a
Column/ListViewinside another unbounded-height ancestor (e.g. aColumninside aSingleChildScrollViewwith noExpanded/shrinkWrap). Give it a bound:Expanded,SizedBox, orshrinkWrap: truewhen genuinely short. - "
InputDecorator... unbounded width" — aTextField/TextFormFieldinside aRowwith noExpanded/Flexiblewrapping it. - "
RenderFlexoverflowed by N pixels" — the matrix-test failure mode (seemobile-visual-self-review); fix by deciding layout from available width, not by shrinking content to fit. - "Incorrect use of
ParentDatawidget" — a widget meant for one parent (Expanded,Positioned) used under the wrong parent type (notFlex/Stack). The fix is almost always removing a stray wrapper, not adding one. - Ignore a cascading "RenderBox was not laid out" once you've fixed the error above it — it's usually fallout from the first failure, not a separate bug.
Version note (Flutter 3.47+)
material_ui/cupertino_ui are now separate packages from the bundled Material/Cupertino libraries; don't run dart fix --apply --code=migrate_design_widgets or otherwise migrate a repo to them unless the task explicitly asks — follow what the repo already uses.
Common Mistakes
StatefulWidgetholding data that came from an API — that's app state, lift it out.Widget _buildHeader()helper methods instead of real widget classes.- Hardcoded colors/sizes instead of the theme.
- Missing
conston static subtrees → needless rebuilds. - Choosing layout by
MediaQuery.of(context).sizeor an orientation/device check instead ofLayoutBuilder/MediaQuery.sizeOf. textScaleFactor/withOpacityinstead ofTextScaler/Color.withValues.
Red Flags
- A
buildmethod you scroll to read. setStatemutating something a service should own.Color(0xFF...)/ magic paddings outside the theme file.- A layout branch keyed on
Theme.of(context).platformorMediaQuery.orientationOfinstead of width.
04 同仓库更多 Skills
visual-craft
暂无简介
ux-copy
Use when you write any words a user reads in a mockup or a hand-off - content language and voice, buttons, labels, errors, empty states, confirmations, numbers and dates, and the longest-string check
screen-mockup-html
Use when you draw screens as the design task's HTML mockup - ONE canvas document holding every screen and every variant side by side, the sanitizer-safe recipe, phone and wide frames, the states grid, static control states, and the loopback self-check with screenshots at 375, 768 and 1440 attached to the task
performance-awareness
How the performance score moves for your role. Use when the score context shows a declining trend, or before handing off work you have not self-checked against every criterion.
design-variants
Use when a screen design needs variants - how many, variants as side-by-side rows on the one canvas, what makes two variants genuinely different, recommending one, how the human's choice is read, and narrowing to the chosen one in revision
design-system-authoring
Use when you derive, change or extend a design system - where tokens live per stack, the DTCG token tree, role-based names for both themes, base vs layer vs drift, the DESIGN.md section order, the inventory format, the contrast check and the lint every proposal returns