使用 Expanded Widget 有何效果?Flutter 的 Expanded 更改了行和列子級的約束,指示它們填充可用空間。於是把 Child 包裹在 Expanded 中,看著它成長!😎


以上截圖的程式碼:
class MyApp extends StatelessWidget {
// This widget is the root of your application.
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Happy Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: Center(
child: Column(
children: <Widget>[
Container(
color: Colors.green,
height: 100,
width: 100,
),
Expanded(
child: Container(
color: Colors.amber,
width: 150,
),
),
Container(
color: Colors.blue,
height: 100,
width: 200,
),
],
),
),
);
}
}
可以見到兩張截圖,在螢幕高度不同的狀況下,藍色和綠色的高度固定,而有 Expanded 包裹的黃色,則會跟著螢幕拉高。
有時我們想要依比例來決定空間,我們可以加入 flex 屬性,參考程式碼如下:
class MyApp extends StatelessWidget {
// This widget is the root of your application.
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Happy Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: Center(
child: Column(
children: <Widget>[
Expanded(
flex: 2,
child: Container(
color: Colors.green,
height: 100,
width: 200,
),
),
Expanded(
flex: 1,
child: Container(
color: Colors.amber,
width: 200,
),
),
Expanded(
flex: 2,
child: Container(
color: Colors.blue,
height: 100,
width: 200,
),
)
],
),
),
);
}
}
效果如截圖:


可以見到,無論螢幕如何拉高,三個顏色都會依照比例呈現(2:1:2)。
此用法使用 Web 測試會比較方便~🤓
參考:
Expanded (Flutter Widget of the Week)
隨意留個言吧:)~