弹性布局 Flex
弹性布局允许子组件按照一定比例来分配父容器空间。
https://api.flutter.dev/flutter/widgets/Flex-class.html
Flex
我们可以发现 Column Row 组件都是继承与 Flex,功能非常强大,通常我们直接用 Column Row 即可。
flutter/lib/src/widgets/basic.dart
/// * [Row], for a horizontal equivalent.
/// * [Flex], if you don't know in advance if you want a horizontal or vertical
/// arrangement.
/// * [Expanded], to indicate children that should take all the remaining room.
/// * [Flexible], to indicate children that should share the remaining room but
/// that may size smaller (leaving some remaining room unused).
/// * [SingleChildScrollView], whose documentation discusses some ways to
/// use a [Column] inside a scrolling container.
/// * [Spacer], a widget that takes up space proportional to its flex value.
/// * The [catalog of layout widgets](https://flutter.dev/widgets/layout/).
class Column extends Flex {
...
Expanded
Expanded 只能放在 Flex、Column、Row 中使用
- 把包裹的元素撑开
代码
class FlexPage extends StatelessWidget {
const FlexPage({Key? key}) : super(key: key);
Widget build(BuildContext context) {
return Scaffold(
body: Row(
children: [
Expanded(
child: Container(
color: Colors.amber,
),
),
const FlutterLogo(
size: 32,
),
],
),
);
}
}
输出
- Flex 属性调整比例
代码
children: [
Expanded(
flex: 1,
child: Container(
color: Colors.amber,
),
),
const Expanded(
flex: 2,
child: FlutterLogo(
size: 32,
),
),
],
输出
Spacer
留白撑开,很适合用在标题按钮的场景中
代码
children: [
Container(
width: 50,
color: Colors.amber,
),
const Spacer(),
const FlutterLogo(
size: 32,
),
],
输出