一、Stack
Stack可用来对children进行层叠,children中越往后的组件在上面显示。
构造函数
Stack({
Key key,
this.alignment = AlignmentDirectional.topStart, // 对齐方式
this.textDirection, // 水平的方向
this.fit = StackFit.loose,
this.overflow = Overflow.clip,
List<Widget> children = const <Widget>[],
}) : super(key: key, children: children);
示例
import 'package:flutter/material.dart';
class StackDemo extends StatelessWidget {
@override
Widget build(BuildContext context) {
// TODO: implement build
return Stack(
alignment: AlignmentDirectional.topStart,
textDirection: TextDirection.ltr,
fit: StackFit.loose,
overflow: Overflow.clip,
children: <Widget>[
Container(
width: 120,
height: 120,
color: Colors.red,
),
Container(
width: 100,
height: 100,
color: Colors.green,
),
Container(
width: 80,
height: 80,
color: Colors.yellow,
),
],
);
}
}
效果
二、Stack结合Align、Positioned使用
Stack中的children都是层层进行叠加的,通过Align或Positioned可将这些层叠组件分开,实现视觉上的分离:
2.1 Stack与Align
class StackAlignDemo extends StatelessWidget{
@override
Widget build(BuildContext context) {
// TODO: implement build
return ConstrainedBox(
constraints: BoxConstraints.expand(),
child: Stack(
children: <Widget>[
Align(
alignment: Alignment.topLeft,
child: Icon(Icons.settings, size: 30,),
),
Align(
alignment: Alignment.topRight,
child: Icon(Icons.add_location, size: 30,),
),
Align(
alignment: Alignment(-1, 0.9),
child: Icon(Icons.forward, size: 30,),
),
Align(
alignment: Alignment(1, 0.9),
child: Icon(Icons.home, size: 30,),
),
Align(
alignment: Alignment.center,
child: Icon(Icons.center_focus_strong, size: 40,),
)
],
),
);
}
}
效果
2.2 Stack与Positioned
class StackPositionedDemo extends StatelessWidget{
@override
Widget build(BuildContext context) {
// TODO: implement build
return Stack(
children: <Widget>[
Positioned(
top: 0,
left: 0,
child: Icon(Icons.settings, size: 30,),
),
Positioned(
top: 0,
right: 0,
child: Icon(Icons.add_location, size: 30,),
),
Positioned(
left: 0,
bottom: 20,
child: Icon(Icons.forward, size: 30,),
),
Positioned(
right: 0,
bottom: 20,
child: Icon(Icons.home, size: 30,),
),
Positioned.fill( // 居中
child: Icon(Icons.center_focus_strong, size: 40,),
)
],
);
}
}
效果
Positioned构造器
const Positioned({
Key key,
this.left,
this.top,
this.right,
this.bottom,
this.width,
this.height,
@required Widget child,
}) : assert(left == null || right == null || width == null),
assert(top == null || bottom == null || height == null),
super(key: key, child: child);