Flutter中Expanded组件用法
Expanded组件可以使Row、Column、Flex等子组件在其主轴方向上展开并填充可用空间(例如,Row在水平方向,Column在垂直方向)。如果多个子组件展开,可用空间会被其flex factor(表示扩展的速度、比例)分割。
Expanded组件必须用在Row、Column、Flex内,并且从Expanded到封装它的Row、Column、Flex的路径必须只包括StatelessWidgets或StatefulWidgets组件(不能是其他类型的组件,像RenderObjectWidget,它是渲染对象,不再改变尺寸了,因此Expanded不能放进RenderObjectWidget)。
注意一点:在Row中使用Expanded的时候,无法指定Expanded中的子组件的宽度width,但可以指定其高度height。同理,在Column中使用Expanded的时候,无法指定Expanded中的子组件的高度height,可以指定宽度width。
import 'package:flutter/material.dart';
class LayoutDemo extends StatelessWidget {
@override
Widget build(BuildContext context) {
return new Scaffold(
appBar: new AppBar(
title: new Text('水平方向布局'),
),
body: new Row(
children: <Widget>[
new RaisedButton(
onPressed: () {
print('点击红色按钮事件');
},
color: const Color(0xffcc0000),
child: new Text('红色按钮'),
),
new Expanded(
flex: 1,
child: new RaisedButton(
onPressed: () {
print('点击黄色按钮事件');
},
color: const Color(0xfff1c232),
child: new Text('黄色按钮'),
),
),
new RaisedButton(
onPressed: () {
print('点击粉色按钮事件');
},
color: const Color(0xffea9999),
child: new Text('粉色按钮'),
),
]
),
);
}
}
void main() {
runApp(
new MaterialApp(
title: 'Flutter教程',
home: new LayoutDemo(),
),
);
}
效果图如下: