10、弹性布局(Flex Expanded)

发布时间 2023-11-16 19:49:27作者: 鲤斌

自定义的IconContainer

class IconContainer extends StatelessWidget {
  Color color;
  IconData icon;
  // IconContainer(this.icon ,{super.key,required this.color}); // 与下方效果一样
    // IconContainer(this.icon ,{Key? key,required this.color}) : super(key: key);
  IconContainer(this.icon ,{Key? key, this.color=Colors.red}) : super(key: key); //可传入颜色(也可以不用传入颜色)

  @override
  Widget build(BuildContext context) {
    return Container(
      alignment: Alignment.center, //内容居中
      color: color,
      height: double.infinity,
      width: double.infinity,
      child: Icon(icon,size: 50,),
    );
  }
}
 
Flex 组件可以沿着水平或垂直方向排列子组件,如果你知道主轴方向,使用 Row 或 Column 会方便一
些,因为 Row 和 Column 都继承自 Flex ,参数基本相同,所以能使用Flex的地方基本上都可以使用
Row 或 Column 。 Flex 本身功能是很强大的,它也可以和 Expanded 组件配合实现弹性布局 。

水平弹性布局

(1)

class MyApp extends StatelessWidget {
  const MyAPP({super.key});

  @override
  Widget build(BuildContext context) {
    return Row(
      children: [
        Expanded(flex: 2,child:  IconContainer(Icons.ac_unit,color: Colors.yellow),//元素设置宽度没有效果
        ),
        Expanded(flex: 2,child:  IconContainer(Icons.home_max,color: Color.fromARGB(255, 226, 12, 47)),
        ),
        Expanded(flex: 1,child:  IconContainer(Icons.ac_unit,color: Color.fromARGB(255, 9, 31, 155)),
        ),
      ],
    );
  }
}

(2)

class HomePage2 extends StatelessWidget {
const HomePage2({Key? key}) : super(key: key);
@override
Widget build(BuildContext context) {
return Flex(
//  direction: Axis.vertical, // 垂直
direction: Axis.horizontal, //水平
children: [
Expanded(flex: 2, child: IconContainer(Icons.home, color: Colors.red)),
Expanded(
flex: 1,
child: IconContainer(Icons.search, color: Colors.orange),
)],
);
}}

垂直弹性布局

(1)

class MyRow extends StatelessWidget {
  const MyRow({super.key});

  @override
  Widget build(BuildContext context) {
    return Column(
      children: [
        Expanded(flex: 2,child:  IconContainer(Icons.ac_unit,color: Colors.yellow),//元素设置高度没有效果
        ),
        Expanded(flex: 2,child:  IconContainer(Icons.home_max,color: Color.fromARGB(255, 226, 12, 47)),
        ),
        Expanded(flex: 1,child:  IconContainer(Icons.ac_unit,color: Color.fromARGB(255, 9, 31, 155)),
        ),
      ],);
  }}

(2)

class HomePage2 extends StatelessWidget {
const HomePage2({Key? key}) : super(key: key);
@override
Widget build(BuildContext context) {
return Flex(
 direction: Axis.vertical, // 垂直
 //direction: Axis.horizontal, //水平
children: [
Expanded(flex: 2, child: IconContainer(Icons.home, color: Colors.red)),
Expanded(
flex: 1,
child: IconContainer(Icons.search, color: Colors.orange),
)],
);
}}