前言
層疊布局,即子組件可以根據距父容器四個角的位置來確定自身的位置。絕對定位運行子組件堆疊起來,即按照代碼中聲明的順序。
Flutter中使用Stack和Positioned這兩個組件來配合實現絕對定位,Stack允許子組件堆疊,而Positioned用於根據Stack的四個角來確定子組件的位置。
接口描述
Stack({
Key key,
// 此參數決定如何去對齊沒有定位(沒有使用Positioned)或部分定位的子組件。
// 所謂部分定位,在這里特指沒有在某一個軸上定位:left、right為橫軸,top、bottom為縱軸,只要包含某個軸上的一個定位屬性就算在該軸上有定位。
this.alignment = AlignmentDirectional.topStart,
// 和Row、Wrap的textDirection功能一樣,都用於確定alignment對齊的參考系,
// 即:textDirection的值為TextDirection.ltr,則alignment的start代表左,end代表右,即從左往右的順序;
// textDirection的值為TextDirection.rtl,則alignment的start代表右,end代表左,即從右往左的順序。
this.textDirection,
// 參數用於確定沒有定位的子組件如何去適應Stack的大小。
// StackFit.loose表示使用子組件的大小,StackFit.expand表示擴伸到Stack的大小。
this.fit = StackFit.loose,
// 此屬性決定如何顯示超出Stack顯示空間的子組件;值為Overflow.clip時,超出部分會被剪裁(隱藏),值為Overflow.visible 時則不會。
this.overflow = Overflow.clip,
List<Widget> children = const <Widget>[],
})
const Positioned({
Key key,
// left、top 、right、 bottom分別代表離Stack左、上、右、底四邊的距離
this.left,
this.top,
this.right,
this.bottom,
// width和height用於指定需要定位元素的寬度和高度。
this.width,
this.height,
@required Widget child,
})
代碼示例
import 'package:flutter/material.dart';
class StackTest extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('層疊布局(Stack和Positioned)'),
),
// 通過ConstrainedBox來確保Stack占滿屏幕
body: ConstrainedBox(
constraints: BoxConstraints.expand(),
child: Stack(
// 指定未定位或部分定位widget的對齊方式
alignment: Alignment.center,
// 未定位widget會占滿Stack整個空間
fit: StackFit.expand,
children: <Widget>[
Container(
child: Text('Hello world', style: TextStyle(color: Colors.white),),
color: Colors.red,
),
Positioned(
left: 18.0,
child: Text('I am hah'),
),
Container(
child: Text('Hello ', style: TextStyle(color: Colors.white),),
color: Colors.red,
),
Positioned(
top:18.0,
child: Text('Your dear!'),
),
],
),
),
);
}
}