adaptive-layout
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChineseAdaptive Layout
自适应布局
Adapt to the space you are given, never to the device you think you are on. A phone in a foldable's front display, a resized desktop window, and a tablet in split-screen all defeat checks — but they all report their real constraints. Branch on width, not hardware.
Platform.isXRead the reference for the task at hand:
- — the Material 3 window size-class breakpoints as a shared vocabulary, the
references/window-size-classes.mdenum pattern,WindowSizeClass/MediaQuery.sizeOf/paddingOfvsviewInsetsOf, readable max-width, SafeArea and display cutouts, keyboard insets, orientation, foldable hinge awareness..of - — single-pane-navigate vs side-by-side two-pane, choosing the navigation affordance by width and coordinating with the go_router shell, keeping selection state in a Notifier so both panes agree.
references/list-detail-and-navigation.md
Run before a PR.
scripts/check_adaptive.sh适应分配给你的可用空间,而不是你以为所在的设备。折叠屏前置显示屏上的手机、被调整大小的桌面窗口,以及分屏中的 tablet,都会让 检查失效——但它们都会报告真实的 constraints。请根据宽度分支,而不是硬件。
Platform.isX阅读与当前任务对应的参考资料:
- ——作为共享词汇表的 Material 3 窗口尺寸分类断点、
references/window-size-classes.md枚举模式、WindowSizeClass/MediaQuery.sizeOf/paddingOf与viewInsetsOf的对比、可读内容的最大宽度、SafeArea 和显示屏缺口、键盘 insets、方向、折叠屏铰链感知。.of - ——单窗格导航与并排双窗格、根据宽度选择导航形式并与 go_router shell 配合、通过 Notifier 保存选择状态,使两个窗格保持一致。
references/list-detail-and-navigation.md
提交 PR 前运行 。
scripts/check_adaptive.shNon-negotiable rules
不可违背的规则
-
Adapt by constraints/size, never by device or platform. No/
Platform.isAndroid/Platform.isIOSto pick a layout. UsekIsWeb(local box constraints) orLayoutBuilder(window size). WHY: a resized window, split-screen, and foldable all break device checks; constraints are always true.MediaQuery.sizeOf(context) -
Use the Material 3 window size classes as the breakpoint vocabulary. Compact, medium
<600, expanded600–840, large840–1200, extra-large1200–1600(logical px width). WHY: these are STANDARD structural breakpoints (not design tokens); one shared enum keeps every screen's breakpoints identical.≥1600 -
Read the narrowest MediaQuery aspect:/
sizeOf/paddingOf/viewInsetsOf, notviewPaddingOf. WHY:MediaQuery.of(context)subscribes the widget to EVERY MediaQuery change (keyboard, rotation, text scale); the aspect getters rebuild only when that one field changes — see.of.flutter-performance -
Pick the navigation affordance by width, not by a per-screen guess.(compact) →
NavigationBar(medium/expanded) →NavigationRail(large). Decide once in the shell. WHY: mixing affordances across screens disorients; one width→affordance map is consistent by construction. Coordinate withNavigationDrawer'snavigation-and-routing.StatefulShellRoute -
List-detail collapses to one pane on compact and splits on expanded. Compact: the list navigates to a detail route. Expanded: list and detail sit side-by-side; selection is shared state. WHY: two panes on a phone are unreadable; one pane on a desktop wastes 70% of the width.
-
Never lock orientation (to force portrait). WHY: it breaks tablets, foldables, and accessibility mounts. Let the size classes handle both orientations.
SystemChrome.setPreferredOrientations -
Constrain readable content with a max width; use/
Flexible/Expanded, not fixed pixel widths, for top-level regions. WHY: full-width body text on a wide screen is unreadable (~40–75 chars/line is legible); fixed region widths overflow or leave dead space.FractionallySizedBox -
Wrap edge content inand respect display cutouts + keyboard insets. Read cutouts/system bars via
SafeArea/MediaQuery.paddingOf; the keyboard viaviewPaddingOf. WHY: notches, punch-holes, and the on-screen keyboard occlude content that ignores insets.MediaQuery.viewInsetsOf -
Never assume a fixed cell/row height. Large text scale can double a cell's height; let content size itself. WHY: a hardcodedclips at 200% text scale — see
SizedBox(height: 48)andaccessibility-as-code.widget-composition -
Verify across sizes with a golden matrix, not one device. Snapshot each adaptive screen at compact/medium/expanded (+ largest text, LTR/RTL). WHY: adaptive bugs only appear at the breakpoint you did not open — see.
widget-golden-and-a11y-testing
-
始终根据 constraints/尺寸进行适配,绝不根据设备或平台。 不得使用/
Platform.isAndroid/Platform.isIOS来选择布局。使用kIsWeb(本地 box constraints)或LayoutBuilder(窗口尺寸)。原因:调整大小的窗口、分屏和折叠屏都会破坏设备检查;constraints 始终真实可靠。MediaQuery.sizeOf(context) -
使用 Material 3 窗口尺寸分类作为断点词汇表。 Compact、medium
<600、expanded600–840、large840–1200、extra-large1200–1600(逻辑像素宽度)。原因:这些是标准化的结构性断点(而非 design tokens);使用一个共享 enum 可以确保每个屏幕的断点完全一致。≥1600 -
按需读取 MediaQuery 的具体维度:/
sizeOf/paddingOf/viewInsetsOf,而不是viewPaddingOf。 原因:MediaQuery.of(context)会让 widget 订阅每一次 MediaQuery 变化(键盘、旋转、文字缩放);特定维度 getter 仅在对应字段变化时触发重建——参见.of。flutter-performance -
根据宽度选择导航形式,而不是为每个屏幕单独猜测。(compact)→
NavigationBar(medium/expanded)→NavigationRail(large)。在 shell 中统一决定一次。原因:不同屏幕混用导航形式会让用户迷失;一张统一的宽度→导航形式映射表从结构上保证一致性。与NavigationDrawer的navigation-and-routing配合使用。StatefulShellRoute -
列表-详情布局在 compact 模式下折叠为一个窗格,在 expanded 模式下拆分为两个窗格。 Compact:列表导航至详情 route。Expanded:列表和详情并排显示;选择状态为共享状态。原因:手机上的两个窗格难以阅读;桌面上的单个窗格则会浪费 70% 的宽度。
-
绝不锁定方向(不要使用强制竖屏)。原因:这会破坏 tablet、折叠屏和无障碍支撑场景。让尺寸分类同时处理两种方向。
SystemChrome.setPreferredOrientations -
使用最大宽度限制可读内容;顶层区域使用/
Flexible/Expanded,不要使用固定像素宽度。 原因:在宽屏幕上使用全宽正文难以阅读(每行约 40–75 个字符才易于阅读);固定区域宽度会造成溢出或留下大片空白。FractionallySizedBox -
使用包裹边缘内容,并兼顾显示屏缺口和键盘 insets。 通过
SafeArea/MediaQuery.paddingOf读取缺口/系统栏;通过viewPaddingOf读取键盘。原因:刘海、挖孔和屏幕键盘会遮挡忽略 insets 的内容。MediaQuery.viewInsetsOf -
绝不假设单元格/行具有固定高度。 较大的文字缩放可能会让单元格高度翻倍;应让内容自行决定尺寸。原因:硬编码的会在 200% 文字缩放下裁切内容——参见
SizedBox(height: 48)和accessibility-as-code。widget-composition -
通过 golden matrix 验证所有尺寸,而不是只验证一台设备。 在 compact/medium/expanded 下为每个自适应屏幕生成快照(还要覆盖最大文字、LTR/RTL)。原因:自适应问题只会出现在你没有打开过的断点——参见。
widget-golden-and-a11y-testing
Size classes as one shared enum
将尺寸分类定义为统一的共享 enum
Define the breakpoints once; every screen reads the same map.
dart
enum WindowSizeClass { compact, medium, expanded, large, extraLarge }
WindowSizeClass windowSizeClassFor(double width) => switch (width) {
< 600 => WindowSizeClass.compact,
< 840 => WindowSizeClass.medium,
< 1200 => WindowSizeClass.expanded,
< 1600 => WindowSizeClass.large,
_ => WindowSizeClass.extraLarge,
};
// In a widget: rebuilds only when the window SIZE changes.
final sizeClass = windowSizeClassFor(MediaQuery.sizeOf(context).width);Prefer when the decision depends on the LOCAL box (a widget inside a split view, a card grid), and when it depends on the whole window (the top-level shell).
LayoutBuilderMediaQuery.sizeOfdart
// Local constraints drive a card grid's column count.
LayoutBuilder(
builder: (context, constraints) {
final columns = constraints.maxWidth ~/ 280; // min card width, structural
return GridView.count(crossAxisCount: columns.clamp(1, 4), children: cards);
},
);只定义一次断点;每个屏幕都读取同一映射。
dart
enum WindowSizeClass { compact, medium, expanded, large, extraLarge }
WindowSizeClass windowSizeClassFor(double width) => switch (width) {
< 600 => WindowSizeClass.compact,
< 840 => WindowSizeClass.medium,
< 1200 => WindowSizeClass.expanded,
< 1600 => WindowSizeClass.large,
_ => WindowSizeClass.extraLarge,
};
// In a widget: rebuilds only when the window SIZE changes.
final sizeClass = windowSizeClassFor(MediaQuery.sizeOf(context).width);当决策取决于 LOCAL box(split view 内的 widget、卡片网格)时,优先使用 ;当决策取决于整个窗口(顶层 shell)时,使用 。
LayoutBuilderMediaQuery.sizeOfdart
// Local constraints drive a card grid's column count.
LayoutBuilder(
builder: (context, constraints) {
final columns = constraints.maxWidth ~/ 280; // min card width, structural
return GridView.count(crossAxisCount: columns.clamp(1, 4), children: cards);
},
);Readable width and flexible regions
可读宽度与弹性区域
dart
// Center and cap body text to a legible measure; never full-bleed on desktop.
Center(
child: ConstrainedBox(
constraints: const BoxConstraints(maxWidth: 720), // structural readable cap
child: article,
),
);
// Split a wide body proportionally, not with magic fixed widths.
Row(
children: [
Expanded(flex: 2, child: primaryPane),
Expanded(flex: 3, child: secondaryPane),
],
);dart
// Center and cap body text to a legible measure; never full-bleed on desktop.
Center(
child: ConstrainedBox(
constraints: const BoxConstraints(maxWidth: 720), // structural readable cap
child: article,
),
);
// Split a wide body proportionally, not with magic fixed widths.
Row(
children: [
Expanded(flex: 2, child: primaryPane),
Expanded(flex: 3, child: secondaryPane),
],
);Insets, cutouts, keyboard, foldables
Insets、显示屏缺口、键盘与折叠屏
dart
// Keyboard height: rebuilds only when the keyboard shows/hides.
final keyboard = MediaQuery.viewInsetsOf(context).bottom;
// Notch/system-bar padding without subscribing to text-scale/rotation changes.
final safeTop = MediaQuery.paddingOf(context).top;
// Foldable: a vertical fold/hinge spanning the full height => split around it.
final seam = MediaQuery.displayFeaturesOf(context)
.where((f) =>
(f.type == DisplayFeatureType.fold ||
f.type == DisplayFeatureType.hinge) &&
f.bounds.top == 0 && // starts at the top edge...
f.bounds.width < f.bounds.height) // ...taller than wide => vertical
.firstOrNull; // firstOrNull: import 'package:collection/collection.dart';Wrap the outermost interactive region in ; opt specific edges out () when a or scrolling body should reach the edge.
SafeAreabottom: falseNavigationBardart
// Keyboard height: rebuilds only when the keyboard shows/hides.
final keyboard = MediaQuery.viewInsetsOf(context).bottom;
// Notch/system-bar padding without subscribing to text-scale/rotation changes.
final safeTop = MediaQuery.paddingOf(context).top;
// Foldable: a vertical fold/hinge spanning the full height => split around it.
final seam = MediaQuery.displayFeaturesOf(context)
.where((f) =>
(f.type == DisplayFeatureType.fold ||
f.type == DisplayFeatureType.hinge) &&
f.bounds.top == 0 && // starts at the top edge...
f.bounds.width < f.bounds.height) // ...taller than wide => vertical
.firstOrNull; // firstOrNull: import 'package:collection/collection.dart';将最外层交互区域包裹在 中;当 或可滚动主体应延伸到屏幕边缘时,可以针对特定边将其排除()。
SafeAreaNavigationBarbottom: falseNavigation affordance by width
根据宽度选择导航形式
dart
// One place decides the shell chrome; screens stay affordance-agnostic.
Widget shellFor(WindowSizeClass sc, {required Widget body, required int index}) {
return switch (sc) {
WindowSizeClass.compact =>
Scaffold(body: body, bottomNavigationBar: _NavBar(index: index)),
WindowSizeClass.medium || WindowSizeClass.expanded =>
Scaffold(body: Row(children: [_Rail(index: index), Expanded(child: body)])),
WindowSizeClass.large || WindowSizeClass.extraLarge =>
Scaffold(body: Row(children: [_Drawer(index: index), Expanded(child: body)])),
};
}See for the full shell and for the two-pane pattern.
examples/adaptive_scaffold.dartexamples/list_detail_pane.dartdart
// One place decides the shell chrome; screens stay affordance-agnostic.
Widget shellFor(WindowSizeClass sc, {required Widget body, required int index}) {
return switch (sc) {
WindowSizeClass.compact =>
Scaffold(body: body, bottomNavigationBar: _NavBar(index: index)),
WindowSizeClass.medium || WindowSizeClass.expanded =>
Scaffold(body: Row(children: [_Rail(index: index), Expanded(child: body)])),
WindowSizeClass.large || WindowSizeClass.extraLarge =>
Scaffold(body: Row(children: [_Drawer(index: index), Expanded(child: body)])),
};
}完整的 shell 请参阅 ,双窗格模式请参阅 。
examples/adaptive_scaffold.dartexamples/list_detail_pane.dartAnti-patterns
反模式
- to choose a layout. Branch on
if (Platform.isIOS) ... else ....MediaQuery.sizeOf(context).width - — subscribes to every MediaQuery change. Use
MediaQuery.of(context).size.width.MediaQuery.sizeOf(context) - to dodge landscape layout. Support both.
SystemChrome.setPreferredOrientations([DeviceOrientation.portraitUp]) - or
Container(width: 375)sizing a top-level pane. UseSizedBox(width: 320)/Expanded/Flexible/FractionallySizedBox.ConstrainedBox - A flag threaded everywhere. Compute a
bool isTablet = MediaQuery.of(context).size.shortestSide > 600from width at the shell.WindowSizeClass - Two panes shown on compact width, forcing horizontal scroll. Collapse to one pane and navigate.
- Full-width paragraphs on desktop with no max-width. Cap the measure.
- Assuming the keyboard is hidden — content jumps under it. Pad by .
MediaQuery.viewInsetsOf(context).bottom
- 使用 选择布局。请根据
if (Platform.isIOS) ... else ...进行判断。MediaQuery.sizeOf(context).width - ——会订阅每一次 MediaQuery 变化。请使用
MediaQuery.of(context).size.width。MediaQuery.sizeOf(context) - 使用 逃避横屏布局。应同时支持两种方向。
SystemChrome.setPreferredOrientations([DeviceOrientation.portraitUp]) - 使用 或
Container(width: 375)设置顶层窗格尺寸。请使用SizedBox(width: 320)/Expanded/Flexible/FractionallySizedBox。ConstrainedBox - 在各处传递 标志。请在 shell 中根据宽度计算
bool isTablet = MediaQuery.of(context).size.shortestSide > 600。WindowSizeClass - 在 compact 宽度下显示两个窗格,导致强制横向滚动。应折叠为一个窗格并进行导航。
- 桌面端正文占满全宽且没有最大宽度限制。应限制可读内容宽度。
- 假设键盘处于隐藏状态——内容会跳到键盘下方。应通过 添加内边距。
MediaQuery.viewInsetsOf(context).bottom
Definition of done
完成标准
- No /
Platform.is*/kIsWebused to select a layout (platform-specific plugins are fine).dart:io - Breakpoints come from the shared helper, not ad-hoc numbers scattered per screen.
WindowSizeClass - MediaQuery is read via /
sizeOf/paddingOf/viewInsetsOf, notviewPaddingOf..of - Navigation affordance is chosen by width in ONE place (the shell), coordinated with .
navigation-and-routing - List-detail screens collapse to one pane on compact and split on expanded, sharing selection state.
- No fixed pixel widths on top-level regions; readable content is max-width capped.
- Orientation is not locked; edge content uses ; keyboard insets are respected.
SafeArea - Golden matrix covers compact/medium/expanded (+ largest text, RTL).
- passes.
scripts/check_adaptive.sh
- 未使用 /
Platform.is*/kIsWeb选择布局(特定平台的 plugin 除外)。dart:io - 断点来自共享的 helper,而不是散落在各屏幕中的临时数字。
WindowSizeClass - 通过 /
sizeOf/paddingOf/viewInsetsOf读取 MediaQuery,而不是使用viewPaddingOf。.of - 在一个位置(shell)根据宽度选择导航形式,并与 配合。
navigation-and-routing - 列表-详情屏幕在 compact 模式下折叠为一个窗格,在 expanded 模式下拆分为两个窗格,并共享选择状态。
- 顶层区域不使用固定像素宽度;可读内容设置最大宽度上限。
- 不锁定方向;边缘内容使用 ;兼顾键盘 insets。
SafeArea - Golden matrix 覆盖 compact/medium/expanded(还要覆盖最大文字、RTL)。
- 执行通过。
scripts/check_adaptive.sh
Related skills
相关 skills
- — structural layout primitives, computed sizing, edge-to-edge vs SafeArea, never-fixed cell heights.
widget-composition - — the
navigation-and-routingthis shell renders; width picks the chrome, routes pick the branch.StatefulShellRoute - — why
flutter-performance/sizeOfbeatselectfor rebuild scope..of - — large text scale interacts with every adaptive cell.
accessibility-as-code - — the device × text-scale × RTL golden matrix that proves adaptivity.
widget-golden-and-a11y-testing - — where shared list-detail selection lives.
state-management-riverpod
- ——结构性布局原语、计算式尺寸、edge-to-edge 与 SafeArea、绝不固定单元格高度。
widget-composition - ——此 shell 渲染的
navigation-and-routing;宽度选择导航框架,routes 选择分支。StatefulShellRoute - ——解释为何
flutter-performance/sizeOf比select具有更精确的重建范围。.of - ——大文字缩放会与每个自适应单元格产生交互。
accessibility-as-code - ——通过设备 × 文字缩放 × RTL 的 golden matrix 验证自适应能力。
widget-golden-and-a11y-testing - ——共享列表-详情选择状态的存放位置。
state-management-riverpod
References
参考资料
- Material 3 layout / window size classes: https://m3.material.io/foundations/layout/applying-layout/window-size-classes
- Adaptive & responsive design (Flutter): https://docs.flutter.dev/ui/adaptive-responsive
- API (aspect getters): https://api.flutter.dev/flutter/widgets/MediaQuery-class.html
MediaQuery - : https://api.flutter.dev/flutter/widgets/LayoutBuilder-class.html
LayoutBuilder - : https://api.flutter.dev/flutter/material/NavigationRail-class.html
NavigationRail - / foldables: https://api.flutter.dev/flutter/dart-ui/DisplayFeature-class.html
DisplayFeature
- Material 3 布局/窗口尺寸分类:https://m3.material.io/foundations/layout/applying-layout/window-size-classes
- 自适应与响应式设计(Flutter):https://docs.flutter.dev/ui/adaptive-responsive
- API(特定维度 getter):https://api.flutter.dev/flutter/widgets/MediaQuery-class.html
MediaQuery - :https://api.flutter.dev/flutter/widgets/LayoutBuilder-class.html
LayoutBuilder - :https://api.flutter.dev/flutter/material/NavigationRail-class.html
NavigationRail - /折叠屏:https://api.flutter.dev/flutter/dart-ui/DisplayFeature-class.html
DisplayFeature