我們在排列介面時,時常會使用 Row 或 Column,但有時候會超出螢幕,此時該怎麼辦呢?🤔
我們可以改用 Wrap Widget,它擁有跟 Row 或 Column 類似的一些屬性,某些狀況是可以取代之。
以下截圖,是以 Row 和 Column 為例。


可見到右邊和下面介面超出顯示範圍。
上截圖的程式碼:
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: Column(// Row
children: <Widget>[
Container(
color: Colors.green,
height: 100,
width: 100,
),
Container(
color: Colors.red,
height: 100,
width: 100,
),
Container(
color: Colors.blue,
height: 100,
width: 100,
),
Container(
color: Colors.yellow,
height: 100,
width: 150,
),
Container(
color: Colors.black,
height: 100,
width: 150,
),
],
),
);
}
}
接著我們改用 Wrap,在 Row 的例子中會有什麼效果呢?
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: Wrap(
// spacing: 8.0, // gap between adjacent chips
// runSpacing: 50.0, // gap between lines
// alignment: WrapAlignment.center,
runAlignment: WrapAlignment.center,
// direction: Axis.vertical,
children: <Widget>[
Container(
color: Colors.green,
height: 100,
width: 100,
),
Container(
color: Colors.red,
height: 100,
width: 100,
),
Container(
color: Colors.blue,
height: 100,
width: 100,
),
Container(
color: Colors.yellow,
height: 100,
width: 150,
),
Container(
color: Colors.black,
height: 100,
width: 150,
),
],
),
);
}
}
結果如圖,會將超過的介面移至下一行。

再來我們試著把使用其他屬性,反註解來跑效果如何~

是不是更有彈性呢?介面上下左右的距離可以設定。
參考:
Wrap (Flutter Widget of the Week)
隨意留個言吧:)~