層疊布局的子組件可以根據(jù)距父容器四個(gè)角的位置來確定自身的位置。允許子組件堆疊起來(按照代碼中聲明的順序)。Flutter中使用Stack和Positioned這兩個(gè)組件來配合實(shí)現(xiàn)這種效果恋技。Stack允許子組件堆疊,而Positioned用于根據(jù)Stack的四個(gè)角來確定子組件的位置。
1. Stack
源碼如下:
Stack({
this.alignment = AlignmentDirectional.topStart,
this.textDirection,
this.fit = StackFit.loose,
this.overflow = Overflow.clip,
List<Widget> children = const <Widget>[],
})
- alignment
決定如何去對(duì)齊沒有定位(沒有使用Positioned)或部分定位的子組件。所謂部分定位蚕冬,在這里特指沒有在某一個(gè)軸上定位:left、right為橫軸是辕,top囤热、bottom為縱軸,只要包含某個(gè)軸上的一個(gè)定位屬性就算在該軸上有定位获三。 - textDirection
和Row赢乓、Wrap的textDirection功能一樣,都用于確定alignment對(duì)齊的參考系石窑,即:textDirection的值為TextDirection.ltr,則alignment的start代表左蚓炬,end代表右松逊,即從左往右的順序;textDirection的值為TextDirection.rtl植兰,則alignment的start代表右谨朝,end代表左茂缚,即從右往左的順序。 - fit
用于確定沒有定位的子組件如何去適應(yīng)Stack的大小烁兰。StackFit.loose表示使用子組件的大小,StackFit.expand表示擴(kuò)伸到Stack的大小徊都。 - overflow
決定如何顯示超出Stack顯示空間的子組件沪斟;值為Overflow.clip時(shí),超出部分會(huì)被剪裁(隱藏)暇矫,值為Overflow.visible 時(shí)則不會(huì)主之。
代碼示例:
class StackDemo extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Stack(
children: <Widget>[
Container(
width: 100,
height: 100,
color: Colors.redAccent,
),
Container(
width: 90,
height: 90,
color: Colors.green,
),
Container(
width: 80,
height: 80,
color: Colors.orangeAccent,
)
],
);
}
}
代碼運(yùn)行效果圖如下:2. Positioned
源碼如下:
const Positioned({
Key key,
this.left,
this.top,
this.right,
this.bottom,
this.width,
this.height,
@required Widget child,
})
left择吊、top 、right槽奕、 bottom分別代表離Stack左几睛、上、右粤攒、底四邊的距離所森。width和height用于指定需要定位元素的寬度和高度。
ps:Positioned的width夯接、height和其它地方的意義稍微有點(diǎn)區(qū)別焕济,此處用于配合left、top 钻蹬、right吼蚁、 bottom來定位組件,舉個(gè)例子问欠,在水平方向時(shí)肝匆,你只能指定left、right顺献、width三個(gè)屬性中的兩個(gè)旗国,如指定left和width后,right會(huì)自動(dòng)算出(left+width)注整,如果同時(shí)指定三個(gè)屬性則會(huì)報(bào)錯(cuò)能曾,垂直方向同理。
代碼示例:
class PositionedDemo extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Stack(
children: [
Image.asset('assets/images/juren.jpeg'),
Positioned(
left: 0,
right: 0,
bottom: 0,
child: Container(
padding: EdgeInsets.symmetric(horizontal: 8),
color: Color.fromRGBO(0, 0, 0, .5),
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
Text(
'進(jìn)擊的巨人',
style: TextStyle(fontSize: 20, color: Colors.white),
),
IconButton(
icon: Icon(
Icons.favorite,
color: Colors.white,
),
onPressed: () => print('點(diǎn)擊'),
)
],
),
),
),
],
);
}
}
代碼運(yùn)行效果圖如下: