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(),
),
);
}
效果圖如下: