Flex 弹性布局

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,
                      ),
                    ),
                  ],
                ),
              ),
            ),
          ],
        ));
  }
}


最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容