Flex 布局.png
Flex布局允许子组件按照一定比例占据父容器空间,Expanded只能作为Flex的子元素,Row和Column都继承自Flex。
import 'package:flutter/material.dart';
void main() {
runApp(const MaterialApp(
debugShowCheckedModeBanner: false,
home: LayoutWidget(),
));
}
class LayoutWidget extends StatelessWidget {
const LayoutWidget({Key? key}) : super(key: key);
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text('Flex 布局'),
),
body: Column(
children: [
Flex(
//子组件对齐方向 [水平 垂直]
direction: Axis.horizontal,
children: [
Expanded(
//占用1/3空间
flex: 1,
child: Container(
//宽度设置无效
width: 300,
height: 30.0,
color: Colors.red,
),
),
Expanded(
//占用2/3空间
flex: 2,
child: Container(
//宽度设置无效
width: 300,
height: 30.0,
color: Colors.green,
),
),
],
),
Padding(
//设置上部内边距
padding: const EdgeInsets.only(top: 20.0),
//约束盒子大小
child: SizedBox(
height: 100.0,
child: Flex(
direction: Axis.vertical,
children: [
Expanded(
//占用2/4空间
flex: 2,
child: Container(
//高度设置无效
height: 30.0,
color: Colors.red,
),
),
//Spacer 是 Expanded 包装类
const Spacer(
//占用1/4空间
flex: 1,
),
Expanded(
//占用1/4空间
flex: 1,
child: Container(
//高度设置无效
height: 30.0,
color: Colors.green,
),
),
],
),
),
),
],
));
}
}