# 第 4 章 · Flutter 布局：Row / Column / Stack 与约束系统

> 示例工程：`examples/ch04-layout/`
> 运行：`cd examples/ch04-layout && flutter run -d macos`（Linux → `-d linux`、Windows → `-d windows`）
> 验证：`flutter analyze` 0 告警、`flutter test` 10 个用例全绿、`flutter build macos --debug` 真实构建并启动成功

## 4.1 本章目标

- 掌握 Flutter 布局的唯一心法：**约束向下传递，尺寸向上汇报，父级决定位置**；
- 会用 `Row`/`Column`/`Stack`/`Wrap` 组合出常见页面结构，理解 `Expanded`/`Flexible`/`SizedBox` 的区别；
- 能读懂并修复两种最常见的运行时错误：`RenderFlex overflowed` 与 `unbounded height`；
- 会用 `LayoutBuilder` 写响应式布局（桌面窗口拉宽拉窄时切两栏/单栏）；
- 知道 `AspectRatio`、`IntrinsicWidth` 这类"特殊布局"的代价。

对照 C/Go：Win32 的 `MoveWindow(hwnd, x, y, w, h)` 要你**算绝对像素**；Gio/Fyne 要你在绘制时**写出坐标**。Flutter 里你不写坐标，只写"关系"，像素由渲染树算出来——这与 ch02 的"声明式 UI"是同一件事的两面。

## 4.2 唯一的规则：约束向下，尺寸向上

Flutter 的布局协议（`RenderBox.performLayout`）只有三步：

1. 父级把 **`BoxConstraints`（最小/最大宽高）** 交给子级；
2. 子级在自己的约束范围内**决定尺寸**，并向父级汇报；
3. 父级根据子级的尺寸**决定它的位置**。

`BoxConstraints` 就是四个数：`minWidth`、`maxWidth`、`minHeight`、`maxHeight`。几个术语：

| 术语 | 含义 | 例子 |
|------|------|------|
| 松约束（loose） | min = 0，max 有限 | `Center` 给子级 `BoxConstraints(0..∞?)` |
| 紧约束（tight） | min == max | `SizedBox(width: 64)` 给子级宽 64 |
| 无界（unbounded） | max = ∞ | 滚动容器在滚动方向给的约束 |

示例里把当前约束**打印到界面上**，让这件事可见：

```dart
// examples/ch04-layout/lib/src/layout_gallery.dart
body: LayoutBuilder(
  builder: (BuildContext context, BoxConstraints constraints) {
    final bool wide = constraints.maxWidth >= 700;
    return SingleChildScrollView( /* ... */ );
  },
),
```

在 1000×800 的窗口里，`LayoutBuilder` 拿到的真实约束是：

```
父级约束: 0..1000 × 0..744
tight(width): false  tight(height): false
```

高度 744 = 800 − 56（`AppBar` 的高度）。宽度是**松约束**：子级可以比 1000 窄。

**这就是 Flutter 与 CSS 最大的区别**：CSS 是浏览器自上而下流式排版 + 子级可以反过来撑大父级；Flutter 是严格的自上而下约束传递，子级**永远不能**突破父级给的最大值。C/Go 程序员会喜欢这一点：没有"内容撑破容器导致整页重排"的不确定性。

## 4.3 Flex：`Row` / `Column`

`Row`（水平）和 `Column`（垂直）合称 **Flex**。五个参数决定一切：

| 参数 | 作用 | 类比 CSS |
|------|------|----------|
| `mainAxisAlignment` | 主轴对齐（Row 是水平） | `justify-content` |
| `crossAxisAlignment` | 交叉轴对齐 | `align-items` |
| `mainAxisSize` | `max`（占满主轴） / `min`（包裹内容） | `width: 100%` vs `fit-content` |
| `children` | 子级列表 | — |
| `textDirection` | 从右到左的语言支持 | `direction` |

子级怎么分空间：

| Widget | 语义 | C/Go 视角 |
|--------|------|-----------|
| `Expanded(flex: n)` | **强制**占满剩余空间，按 flex 比例分配 | 像 `flex: n`；不能被子级拒绝 |
| `Flexible(flex: n)` | **允许**子级小于分配额（比如文本需要换行时） | "最多给你这么多" |
| `SizedBox(width: 64)` | 固定尺寸 | `MoveWindow(hwnd, x, y, 64, 56)` |
| `Spacer()` | `Expanded(child: SizedBox.shrink())` 的语法糖 | 空白填充 |

```dart
Row(
  children: const [
    Expanded(flex: 1, child: _SizedBox(key: Key('flex-a'), ...)),
    SizedBox(width: 8),
    Expanded(flex: 2, child: _SizedBox(key: Key('flex-b'), ...)),
    SizedBox(width: 8),
    SizedBox(key: Key('fixed-box'), width: 64, height: 56, child: ...),
  ],
)
```

测试断言了真实尺寸关系：

```dart
expect(fixed.width, 64);
expect(b.width / a.width, closeTo(2.0, 0.02));            // flex 1 : 2
expect(a.width + b.width + fixed.width + 16, closeTo(rowWidth, 0.5));
```

**陷阱**：`Expanded` 在**无界约束**下必然报错，因为它"占满剩余空间"而剩余空间是 ∞。两个高频场景：

- `SingleChildScrollView` 里的 `Column` 用 `Expanded`；
- `ListView` 里直接放 `Expanded`。

这正是示例里 `6 个用例之外` 的那两个"故意写错"的测试所演示的，真实错误原文是：

```
RenderFlex children have non-zero flex but incoming height constraints are unbounded.
```

修复方式：去掉 `Expanded` 改用固定高度，或者把滚动容器换成 `Expanded(child: ListView(...))`。

## 4.4 `Stack` / `Positioned`：层叠与绝对定位

```dart
SizedBox(
  height: 150,
  child: Stack(
    children: [
      const Positioned.fill(child: DecoratedBox(/* 渐变背景 */)),
      const Center(child: Text('Positioned.fill 铺满')),
      Positioned(top: 8, right: 8, child: Container(/* badge */)),
    ],
  ),
)
```

- `Stack` 的子级默认按 `alignment`（默认左上）叠放，**后画的在上层**；
- `Positioned` 类似 CSS `position: absolute`，可以同时指定 `left/right/top/bottom`；
- `Positioned.fill` = 四边都 0，铺满父级。

测试里用几何断言验证定位：

```dart
final Rect badge = tester.getRect(find.byKey(const Key('stack-badge')));
final Rect stack = tester.getRect(
  find.ancestor(of: find.byKey(const Key('stack-badge')), matching: find.byType(Stack)).first,
);
expect(stack.right - badge.right, closeTo(8, 0.5));
expect(badge.top - stack.top, closeTo(8, 0.5));
```

> **测试陷阱**：`find.byType(Stack)` 会匹配到框架内部（Scaffold、Material 都有 Stack），必须用 `find.ancestor` / `find.descendant` 限定作用域。示例的第一版就是直接 `find.byType(Stack)`，断言出了 592 这种莫名其妙的宽度——因为匹配到了 `Chip` 内部的 Row。

## 4.5 约束修饰符：`AspectRatio`、`ConstrainedBox`、`IntrinsicWidth`

| Widget | 作用 | 代价 |
|--------|------|------|
| `SizedBox` | 固定尺寸，最常用 | 无 |
| `ConstrainedBox` | 追加额外约束（取交集） | 无 |
| `AspectRatio` | 给定宽度反推高度（或反之） | 无 |
| `FractionallySizedBox` | 按父级尺寸的百分比 | 无 |
| `IntrinsicWidth` / `IntrinsicHeight` | 先问子级"你最想要多大" | **两次布局**，性能敏感处慎用 |

`AspectRatio` 的实验：

```dart
AspectRatio(
  key: const Key('aspect-16-9'),
  aspectRatio: 16 / 9,
  child: /* ... */,
)
```

测试断言 `height / width ≈ 9/16`。视频播放器、图片占位符基本都用它。

## 4.6 滚动容器与"无界约束"

| Widget | 给子级的约束 | 用途 |
|--------|-------------|------|
| `SingleChildScrollView` | 滚动方向 **∞**，另一方向 = 自身宽度 | 一屏内容，整体滚动 |
| `ListView` / `CustomScrollView` | 滚动方向 ∞，逐个构建 | 长列表（惰性构建，ch09 会讲性能） |
| `Expanded(child: ListView())` | 有限高度 | 让列表**只占剩余空间** |

记住一条：**看到 `unbounded` 就先找滚动容器**。

## 4.7 响应式：`LayoutBuilder` 还是 `MediaQuery`

| 手段 | 拿到什么 | 适用 |
|------|----------|------|
| `LayoutBuilder` | **父级给的约束**（局部） | 组件级响应式（本例） |
| `MediaQuery.sizeOf(context)` | 整个窗口/屏幕的逻辑尺寸 | 页面级断点、移动端 |
| `MediaQuery.of(context).orientation` | 横竖屏 | 移动端 |

示例用 `constraints.maxWidth >= 700` 在 700px 处切换："宽屏两栏 / 窄屏单栏"。桌面端用户可以随意拉窗口，所以这个断点是**必须**做的——这是桌面应用和手机应用最大的交互差异之一。

```dart
if (wide)
  Row(
    key: const Key('wide-row'),
    children: const [Expanded(child: _FlexPanel()), SizedBox(width: 16), Expanded(child: _StackPanel())],
  )
else
  const Column(
    key: Key('narrow-column'),
    children: [_FlexPanel(), SizedBox(height: 16), _StackPanel()],
  ),
```

测试里通过改 `tester.view.physicalSize` 模拟 1280 和 420 两种窗口，断言切到了正确的布局且无异常——**桌面端的窗口 resize 是自动化测试能覆盖的**，这一点比 C/Go 的 GUI 强太多。

## 4.8 overflow：黄黑条纹是怎么回事

`Row`/`Column` 在主轴上放不下子级时，会在 debug 模式下画黄黑条纹并打印：

```
A RenderFlex overflowed by 42 pixels on the right.
```

常见原因与修法：

| 原因 | 修法 |
|------|------|
| `Row` 里有 `Text` 太长 | `Expanded`/`Flexible` 包住，或 `Text(overflow: TextOverflow.ellipsis)` |
| 固定像素宽度的子级总和超过父级 | 换成 `flex` 比例 |
| 在窄屏上用 `Row` 排太多东西 | 用 `Wrap` 自动换行（示例里的 `Wrap` 面板） |
| 有 `Positioned` 超出 `Stack` 边界 | `clipBehavior` 或调整尺寸 |

示例里的测试把"错误 → 修复"写成了可执行的断言：

```dart
// 失败：Row 里裸 Text
expect(tester.takeException().toString(), contains('overflowed'));

// 修复：包 Flexible，允许文本在约束内换行
await tester.pumpWidget(/* ...Flexible(child: Text(...))... */);
expect(tester.takeException(), isNull);
```

> **测试陷阱**：一次布局失败往往连锁产生十几条错误，`tester.takeException()` 只会返回一个 "Multiple exceptions (13) were detected..." 的汇总，拿不到原始文案。要断言具体错误信息，得临时接管 `FlutterError.onError`：
>
> ```dart
> final errors = <FlutterErrorDetails>[];
> final void Function(FlutterErrorDetails)? previous = FlutterError.onError;
> FlutterError.onError = errors.add;
> addTearDown(() => FlutterError.onError = previous);
> // ... pumpWidget ...
> expect(errors.first.exception.toString(), contains('unbounded'));
> ```

## 4.9 运行与验证

```bash
cd examples/ch04-layout
flutter pub get
flutter analyze     # No issues found!
flutter test        # All tests passed! (10 个用例)

flutter run -d macos          # 拖动窗口看 700px 断点切换
flutter build macos --debug   # 无图形环境下的等价验证
./build/macos/Build/Products/Debug/ch04_layout.app/Contents/MacOS/ch04_layout
```

本次真实验证：

```
✓ Built build/macos/Build/Products/Debug/ch04_layout.app
[IMPORTANT:...embedder_surface_metal_impeller.mm(53)] Using the Impeller rendering backend (MetalSDF).
flutter: The Dart VM service is listening on http://127.0.0.1:58142/...
```

移动端注意：手机上 `constraints.maxWidth` 是设备逻辑宽度（如 390），`700` 断点永远走单栏分支；真正的平板/折叠屏适配一般用 600/840 这类 Material 断点。

## 附：C/Go 代码对照：弹性布局要手算

```c
/* C / Win32：1:2:固定宽度 三栏，全部自己算（窗口 resize 时要重算） */
int gap = 8, fixed = 64;
int flexSpace = clientWidth - fixed - 2 * gap;
int w1 = flexSpace / 3;
int w2 = flexSpace - w1;

MoveWindow(hFlex1, 0, 0, w1, height, TRUE);
MoveWindow(hFlex2, w1 + gap, 0, w2 - gap, height, TRUE);
MoveWindow(hFixed, clientWidth - fixed, 0, fixed, height, TRUE);
```

```dart
// Flutter：只描述比例，像素由约束系统算
Row(children: const [
  Expanded(flex: 1, child: _Box('flex 1')),
  SizedBox(width: 8),
  Expanded(flex: 2, child: _Box('flex 2')),
  SizedBox(width: 8),
  SizedBox(width: 64, child: _Box('64px')),
]);
```

Win32 里 `WM_SIZE` 一到就要重算所有子窗口；Flutter 里父级的约束变了，`Expanded` 自动重新分配。**这也是为什么 Flutter 的布局代码不需要"更新函数"**。

## 4.10 本章小结 + C/Go 对照清单

| 主题 | C（Win32） | Go（Gio/Fyne） | Flutter | 陷阱 |
|------|-----------|----------------|---------|------|
| 定位 | `MoveWindow(x,y,w,h)` | 绘制时写坐标 | 父级根据子级尺寸决定 | 不要试图"设绝对位置" |
| 尺寸来源 | 你自己算 | 你自己算 | 约束向下、尺寸向上 | 子级不能超过父级 `max` |
| 弹性布局 | 手写比例分配 | 手写 | `Expanded(flex:)` | 无界约束下会崩 |
| 叠放 | 绘制顺序 + 裁剪 | 绘制顺序 | `Stack` + `Positioned` | `find.byType(Stack)` 会误匹配 |
| 换行 | 手写 | 手写 | `Wrap` | — |
| 滚动 | `WS_VSCROLL` + 手写偏移 | 手写 | `SingleChildScrollView` / `ListView` | 滚动方向是无界约束 |
| 响应式 | `WM_SIZE` 消息手算 | 手算 | `LayoutBuilder` / `MediaQuery` | 桌面端必须做 |
| 布局反馈 | 无（画错了自己看） | 无 | 黄黑条纹 + 异常文本 | 用测试固化 |

**给 C/Go 老兵的三句话**：

1. 不要写绝对坐标。你描述的是"关系"（比例、固定、层叠），像素是渲染树算出来的。
2. `Expanded` = 抢剩余空间，`Flexible` = 最多占这么多。搞混这两个是 overflow 的头号来源。
3. 看到 `unbounded` 就去找滚动容器；看到黄黑条纹就去查主轴上的固定宽度。

下一章回到纯 Dart：`Future`/`async`/`await`/`Stream`。你会看到 Dart 为什么敢用**单线程**做并发，以及 `await` 与 goroutine 到底差在哪。
