Flutter基础-010-Flex弹性布局

818 阅读1分钟

Flex与Expanded配合使用,可以按比例分配宽或高

Flex主要属性
  • direction: Axis.horizontal,// 水平方向,Expanded的height有效
  • direction: Axis.vertical,// 垂直方向,Expanded的width有效
  • children 子widget
Expanded主要属性
  • width:宽度,
  • flex:所占比例,多个Expanded之间按比例划分
  • height:高度
  • child:显示的子widget
Axis.vertical

image.png

class _MyHomePageState extends State<MyHomePage> {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(widget.title),
      ),
      body: Flex(
//        direction: Axis.horizontal,// 水平方向,Expanded的height有效
        direction: Axis.vertical,// 垂直方向,Expanded的width有效
        children: <Widget>[
          Expanded(
            flex: 1,
            child: Container(
              height: 20,
              width: 20,
              color: Colors.blue,
            ),
          ),
          Expanded(
            flex: 2,
            child: Container(
              height: 40,
              width: 40,
              color: Colors.green,
            ),
          ),
          Expanded(
            flex: 3,
            child: Container(
              height: 60,
              width: 60,
              color: Colors.orange,
            ),
          ),
        ],
      ),
    );
  }
}

Axis.horizontal,

image.png

class _MyHomePageState extends State<MyHomePage> {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(widget.title),
      ),
      body: Flex(
        direction: Axis.horizontal,// 水平方向,Expanded的height有效
//        direction: Axis.vertical,// 垂直方向,Expanded的width有效
        children: <Widget>[
          Expanded(
            flex: 1,
            child: Container(
              height: 20,
              width: 20,
              color: Colors.blue,
            ),
          ),
          Expanded(
            flex: 2,
            child: Container(
              height: 40,
              width: 40,
              color: Colors.green,
            ),
          ),
          Expanded(
            flex: 3,
            child: Container(
              height: 60,
              width: 60,
              color: Colors.orange,
            ),
          ),
        ],
      ),
    );
  }
}