FlutterCH 04ch04_layout
ch04-layout
Flutter 布局:Row / Column / Stack 与约束系统。完整工程共 100 个文件,其中 60 个文本源文件可在下面在线阅读。
60
在线文本文件
3,632
源码行数
dart / c / yaml
语言
276 KB
打包体积
在线阅读源码
左侧按目录浏览,点击文件切换。右上角可复制代码、复制路径或单独下载文件。在线视图只覆盖文本源码,完整工程请下载 zip。
textxmldartjsonkotlin
60 text files · 3,632 lines
dartlib/src/layout_gallery.dart335 行 · 10 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
// 布局实验场:用 LayoutBuilder 读出父级给的约束,再根据宽度切换"宽屏/窄屏"两套布局。
import 'package:flutter/material.dart';
/// 页面级入口。
class LayoutGalleryPage extends StatelessWidget {
const LayoutGalleryPage({super.key});
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: const Text('布局与约束')),
body: LayoutBuilder(
// LayoutBuilder 把"父级给我的约束"交到你手上。这是 CSS 媒体查询的替代品,
// 也是桌面端做响应式布局的标准手段(移动端通常用 MediaQuery.size)。
builder: (BuildContext context, BoxConstraints constraints) {
final bool wide = constraints.maxWidth >= 700;
// SingleChildScrollView 给子级的是**无界高度**(maxHeight = infinity),
// 所以里面不能用 Expanded——那会抛 "unbounded height" 错误(见 test 里的演示)。
return SingleChildScrollView(
padding: const EdgeInsets.all(16),
child: Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
_ConstraintReport(constraints: constraints),
const SizedBox(height: 16),
if (wide)
Row(
key: const Key('wide-row'),
crossAxisAlignment: CrossAxisAlignment.start,
children: const [
Expanded(child: _FlexPanel()),
SizedBox(width: 16),
Expanded(child: _StackPanel()),
],
)
else
const Column(
key: Key('narrow-column'),
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
_FlexPanel(),
SizedBox(height: 16),
_StackPanel(),
],
),
const SizedBox(height: 16),
const _WrapPanel(),
const SizedBox(height: 16),
const _RatioPanel(),
const SizedBox(height: 16),
const _IntrinsicPanel(),
],
),
);
},
),
);
}
}
/// 显示当前约束:让"约束向下传"这件事可见。
class _ConstraintReport extends StatelessWidget {
const _ConstraintReport({required this.constraints});
final BoxConstraints constraints;
@override
Widget build(BuildContext context) {
final BoxConstraints c = constraints;
return Container(
padding: const EdgeInsets.all(12),
decoration: BoxDecoration(
color: Theme.of(context).colorScheme.surfaceContainerHighest,
borderRadius: BorderRadius.circular(12),
),
child: Text(
key: const Key('constraint-report'),
'父级约束: ${c.minWidth.toStringAsFixed(0)}..${_bound(c.maxWidth)} × '
'${c.minHeight.toStringAsFixed(0)}..${_bound(c.maxHeight)}\n'
'tight(width): ${c.hasTightWidth} tight(height): ${c.hasTightHeight}',
style: const TextStyle(fontFamily: 'monospace', fontSize: 13),
),
);
}
String _bound(double v) => v.isFinite ? v.toStringAsFixed(0) : '∞';
}
/// Flex 演示:一行里三块,按 flex 比例 + 固定宽度分配。
class _FlexPanel extends StatelessWidget {
const _FlexPanel();
@override
Widget build(BuildContext context) {
return _Panel(
title: 'Flex:按比例分剩余空间',
code: 'Row[ Expanded(flex:1), Expanded(flex:2), SizedBox(width:64) ]',
child: Row(
crossAxisAlignment: CrossAxisAlignment.start,
children: const [
Expanded(flex: 1, child: _SizedBox(key: Key('flex-a'), label: 'flex 1', color: Color(0xFF5C6BC0))),
SizedBox(width: 8),
Expanded(flex: 2, child: _SizedBox(key: Key('flex-b'), label: 'flex 2', color: Color(0xFF26A69A))),
SizedBox(width: 8),
SizedBox(
key: Key('fixed-box'),
width: 64,
height: 56,
child: _LabeledBox(label: '64px', color: Color(0xFFEF6C00)),
),
],
),
);
}
}
/// Stack + Positioned:叠放与相对定位,相当于 CSS 的 absolute。
class _StackPanel extends StatelessWidget {
const _StackPanel();
@override
Widget build(BuildContext context) {
return _Panel(
title: 'Stack:层叠 + 相对定位',
code: 'Stack[ Container, Positioned(top:8,right:8, badge) ]',
child: SizedBox(
height: 150,
child: Stack(
children: [
const Positioned.fill(
child: DecoratedBox(
decoration: BoxDecoration(
gradient: LinearGradient(
colors: <Color>[Color(0xFF1E88E5), Color(0xFF8E24AA)],
begin: Alignment.topLeft,
end: Alignment.bottomRight,
),
borderRadius: BorderRadius.all(Radius.circular(12)),
),
),
),
const Center(
child: Text(
'Positioned.fill 铺满',
style: TextStyle(color: Colors.white, fontWeight: FontWeight.w600),
),
),
Positioned(
top: 8,
right: 8,
child: Container(
key: const Key('stack-badge'),
padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 4),
decoration: BoxDecoration(
color: Colors.white,
borderRadius: BorderRadius.circular(999),
),
child: const Text('badge', style: TextStyle(fontSize: 12)),
),
),
],
),
),
);
}
}
/// Wrap:一行放不下就换行,类似 CSS flex-wrap。比手写 LayoutBuilder 省事。
class _WrapPanel extends StatelessWidget {
const _WrapPanel();
@override
Widget build(BuildContext context) {
return _Panel(
title: 'Wrap:自动换行',
code: 'Wrap(spacing: 8, runSpacing: 8, children: [...])',
child: Wrap(
key: const Key('wrap'),
spacing: 8,
runSpacing: 8,
children: [
for (final String tag in const <String>[
'Row',
'Column',
'Stack',
'Wrap',
'Expanded',
'Flexible',
'SizedBox',
'AspectRatio',
'ConstrainedBox',
'IntrinsicWidth',
])
Chip(label: Text(tag)),
],
),
);
}
}
/// 宽高比 + 分数尺寸:AspectRatio 在给定宽度下反推高度。
class _RatioPanel extends StatelessWidget {
const _RatioPanel();
@override
Widget build(BuildContext context) {
return _Panel(
title: 'AspectRatio / FractionallySizedBox',
code: 'AspectRatio(16/9) → 高度 = 宽度 × 9 / 16',
child: AspectRatio(
key: const Key('aspect-16-9'),
aspectRatio: 16 / 9,
child: DecoratedBox(
decoration: BoxDecoration(
color: const Color(0xFFB0BEC5),
borderRadius: BorderRadius.circular(8),
),
child: const Center(child: Text('16 : 9')),
),
),
);
}
}
/// IntrinsicWidth:先问子级"你最想要多宽",再决定自己的宽度。
/// 代价是两次布局,性能敏感的地方不要滥用。
class _IntrinsicPanel extends StatelessWidget {
const _IntrinsicPanel();
@override
Widget build(BuildContext context) {
return _Panel(
title: 'IntrinsicWidth:按内容定宽',
code: 'IntrinsicWidth → 问子级 intrinsic width,代价是双倍布局',
child: IntrinsicHeight(
child: Row(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: const [
_LabeledBox(label: '短', color: Color(0xFF7986CB)),
SizedBox(width: 8),
_LabeledBox(label: '长一些的标签', color: Color(0xFF4DB6AC)),
],
),
),
);
}
}
/// 统一的面板外壳:标题 + 代码提示 + 演示区。
class _Panel extends StatelessWidget {
const _Panel({required this.title, required this.code, required this.child});
final String title;
final String code;
final Widget child;
@override
Widget build(BuildContext context) {
final ThemeData theme = Theme.of(context);
return Card(
margin: EdgeInsets.zero,
child: Padding(
padding: const EdgeInsets.all(12),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(title, style: theme.textTheme.titleMedium),
const SizedBox(height: 2),
Text(
code,
style: TextStyle(
fontFamily: 'monospace',
fontSize: 11,
color: theme.colorScheme.onSurfaceVariant,
),
),
const SizedBox(height: 10),
child,
],
),
),
);
}
}
/// 会自己报告实际宽度的方块——用来在界面上/测试里观察约束的结果。
class _SizedBox extends StatelessWidget {
const _SizedBox({super.key, required this.label, required this.color});
final String label;
final Color color;
@override
Widget build(BuildContext context) {
return LayoutBuilder(
builder: (BuildContext context, BoxConstraints c) {
final String text = c.maxWidth.isFinite
? '$label\n${c.maxWidth.toStringAsFixed(0)}px'
: '$label\n∞';
return _LabeledBox(label: text, color: color);
},
);
}
}
class _LabeledBox extends StatelessWidget {
const _LabeledBox({required this.label, required this.color});
final String label;
final Color color;
@override
Widget build(BuildContext context) {
return Container(
height: 56,
alignment: Alignment.center,
padding: const EdgeInsets.symmetric(horizontal: 6),
decoration: BoxDecoration(
color: color,
borderRadius: BorderRadius.circular(8),
),
child: FittedBox(
// 窄屏时文字自动缩放,而不是溢出报错。
fit: BoxFit.scaleDown,
child: Text(
label,
textAlign: TextAlign.center,
style: const TextStyle(color: Colors.white, fontSize: 12),
),
),
);
}
}
代码构成:text 60 KB · xml 41 KB · dart 18 KB · json 4 KB
本地运行
zip → 解压 → 执行$cd examples/ch04-layout && flutter run -d macos(Linux → -d linux、Windows → -d windows)这个 zip 里有什么
- • 完整工程目录(含 Android / iOS / 桌面平台脚手架)
- • lib / bin / test / native 全部源码与测试
- • pubspec.yaml、锁文件与平台配置文件
- • 已排除 .dart_tool / build / target / ephemeral 等构建产物
已验证
- flutter analyze 0 告警、flutter test 10 个用例全绿、flutter build macos --debug 真实构建并启动成功