
注意:無特殊說明,Flutter版本及Dart版本如下:
- Flutter版本: 1.12.13+hotfix.5
- Dart版本: 2.7.0
Stack
Stack元件可以将子元件疊加顯示,根據子元件的順利依次向上疊加,用法如下:
Stack(
children: <Widget>[
Container(
height: 200,
width: 200,
color: Colors.red,
),
Container(
height: 170,
width: 170,
color: Colors.blue,
),
Container(
height: 140,
width: 140,
color: Colors.yellow,
)
],
)
效果如下:
Stack未定位的子元件大小由
fit
參數決定,預設值是
StackFit.loose
,表示子元件自己決定,
StackFit.expand
表示盡可能的大,用法如下:
Stack(
fit: StackFit.expand,
...
)
Stack未定位的子元件的預設左上角對齊,通過
alignment
參數控制,用法如下:
Stack(
alignment: Alignment.center,
...
)
有沒有注意到
fit
和
alignment
參數控制的都是未定位的子元件,那什麼樣的元件叫做定位的子元件?使用Positioned包裹的子元件就是定位的子元件,用法如下:
Stack(
alignment: Alignment.center,
children: <Widget>[
Container(
height: 200,
width: 200,
color: Colors.red,
),
Positioned(
left: 10,
right: 10,
bottom: 10,
top: 10,
child: Container(
color: Colors.green,
),
)
],
)
Positioned元件可以指定距Stack各邊的距離,效果如下:
如果子元件超過Stack邊界由
overflow
控制,預設是裁剪,下面設定總是顯示的用法:
Stack(
overflow: Overflow.visible,
children: <Widget>[
Container(
height: 200,
width: 200,
color: Colors.red,
),
Positioned(
left: 100,
top: 100,
height: 150,
width: 150,
child: Container(
color: Colors.green,
),
)
],
)
IndexedStack
IndexedStack是Stack的子類,Stack是将所有的子元件疊加顯示,而IndexedStack隻顯示指定的子元件,用法如下:
IndexedStack(
index: _index,
children: <Widget>[
Center(
child: Container(
height: 300,
width: 300,
color: Colors.red,
alignment: Alignment.center,
child: Icon(
Icons.fastfood,
size: 60,
color: Colors.blue,
),
),
),
Center(
child: Container(
height: 300,
width: 300,
color: Colors.green,
alignment: Alignment.center,
child: Icon(
Icons.cake,
size: 60,
color: Colors.blue,
),
),
),
Center(
child: Container(
height: 300,
width: 300,
color: Colors.yellow,
alignment: Alignment.center,
child: Icon(
Icons.local_cafe,
size: 60,
color: Colors.blue,
),
),
),
],
)
通過點選按鈕更新
_index
值,代碼如下:
Row(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
IconButton(
icon: Icon(Icons.fastfood),
onPressed: () {
setState(() {
_index = 0;
});
},
),
IconButton(
icon: Icon(Icons.cake),
onPressed: () {
setState(() {
_index = 1;
});
},
),
IconButton(
icon: Icon(Icons.local_cafe),
onPressed: () {
setState(() {
_index = 2;
});
},
),
],
)
Positioned
Positioned用于定位Stack子元件,Positioned必須是Stack的子元件,基本用法如下:
Stack(
children: <Widget>[
Positioned(
left: 10,
right: 10,
top: 10,
bottom: 10,
child: Container(color: Colors.red),
),
],
)
相關說明:
- 提供
、top
bottom
left
四種定位屬性,分别表示距離上下左右的距離。right
- 隻能用于Stack元件中。
-
left
right
3個參數隻能設定其中2個,因為設定了其中2個,第三個已經确定了,同理width
top
bottom
也隻能設定其中2個。height
Positioned提供便捷的建構方式,比如
Positioned.fromRect
Positioned.fill
等,這些便捷的建構方式萬變不離其宗,隻不過換了一種方式設定
top
bottom
left
right
四種定位屬性。
今天的文章對大家是否有幫助?如果有,請在文章底部留言和點贊,以表示對我的支援,你們的留言、點贊和轉發關注是我持續更新的動力!