我是層疊布局 的搬運工
Flutter 布局(八)- Stack、IndexedStack、GridView詳解
居中
Stack
- 其childWidget 可以層疊到一起,層疊順序:Widget越后創建,層級越靠上
- 可以控制沒有定位的childWidget的布局策略
Stack({
this.alignment = AlignmentDirectional.topStart,
this.textDirection,
this.fit = StackFit.loose,
this.overflow = Overflow.clip,
List<Widget> children = const <Widget>[],
})
-
alignment
決定如何去對齊沒有定位(沒有使用Positioned)或部分定位的子widget。所謂部分定位,在這里特指沒有在某一個軸上定位:left、right為橫軸,top、bottom為縱軸,只要包含某個軸上的一個定位屬性就算在該軸上有定位 -
textDirection
和Row、Wrap的textDirection功能一樣,都用于決定alignment對齊的參考系即:textDirection的值為TextDirection.ltr,則alignment的start代表左,end代表右;textDirection的值為TextDirection.rtl,則alignment的start代表右,end代表左。 -
fit
此參數用于決定沒有定位的子widget如何去適應Stack的大小。StackFit.loose表示使用子widget的大小,StackFit.expand表示擴伸到Stack的大小。 -
overflow
此屬性決定如何顯示超出Stack顯示空間的子widget,值為Overflow.clip時,超出部分會被剪裁(隱藏),值為Overflow.visible 時則不會。
IndexedStack
繼承自Stack,表示只顯示第幾個widget,其他隱藏
Positioned
const Positioned({
Key key,
this.left,
this.top,
this.right,
this.bottom,
this.width,
this.height,
@required Widget child,
})
- left、right、bottom、top分別表示 距離stack的邊的距離
- width、height表示寬高。Widget在指定left與width后,就自動確定了right。如果在設置right,則報錯。其他情況(指定top與height,不能再指定bottom等)類似。
- 只能在Stack 的childs中使用。目前測試,在其他的Widget中使用會報錯。
import 'package:flutter/material.dart';
import 'package:vector_math/vector_math_64.dart' as Vector;
void main() {
runApp(MaterialApp(
home: MyApph(),
));
}
class MyApph extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text("Stack"),
),
//body: Positioned(child: Text("101010")));// 報錯
body: MainView(EdgeInsets.all(10)));
}
}
class MainView extends StatelessWidget {
EdgeInsets _space = EdgeInsets.all(0);
MainView(this._space);
@override
Widget build(BuildContext context) {
return ConstrainedBox(
constraints: BoxConstraints(
maxHeight: 400,
),
child: Stack(
// child: IndexedStack( // indexedStack 繼承自Stack,表示顯示第幾個widget
// index: 2,
fit: StackFit.expand,
///擴展到stack大小
alignment: AlignmentDirectional.center,
children: <Widget>[
Container(
color: Color.fromARGB(100, 200, 100, 0),
),
Positioned(
height: 60,
left: 10,
right: 10,
top: 10,
child: Padding(
padding: EdgeInsets.all(10),
child: Container(
color: Color.fromARGB(100, 50, 100, 0),
child: Center(
child: Text(
"我設置了左右約束,所以 stack alignment 對我無效",
style: TextStyle(color: Color.fromARGB(200, 50, 50, 0)),
),
),
),
),
),
Positioned(
height: 200,
width: 200,
child: Padding(
padding: EdgeInsets.all(10),
child: Container(
color: Color.fromARGB(100, 100, 100, 0),
),
),
),
Positioned(
height: 100,
width: 100,
child: Padding(
padding: EdgeInsets.all(10),
child: Container(
color: Color.fromARGB(100, 200, 50, 0),
),
),
)
],
),
);
}
}