示例工程 ch04-layout
ch04-layout/lib/src/layout_gallery.dart
// 布局实验场:用 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),
),
),
);
}
}