层叠布局
- 子组件根据距父容器四个角的位置来确定自己位置。子元素按照代码中声明的顺序作为层级,最后一个声明的子元素会放置在最上层。Flutter中使用Stack和Positioned这两个组件来配合使用决定子元素的坐标位置。
Stack
Stack({
Key key,
this.alignment = AlignmentDirectional.topStart,
this.textDirection,
this.fit = StackFit.loose,
this.overflow = Overflow.clip,
List<Widget> children = const <Widget>[],
})
alignment:如何对齐堆栈中未定位和部分定位的子元素。
fit :如何调整堆栈中未定位的子元素的大小。
overflow:是否应修剪溢出的部分。默认溢出部分裁剪掉
- 布局行为
Stack的布局行为,根据child是positioned还是non-positioned来区分。
对于positioned的子节点,它们的位置会根据所设置的top、bottom、right以及left属性来确定,这几个值都是相对于Stack的左上角;
对于non-positioned的子节点,它们会根据Stack的aligment来设置位置。
/*
Stack({
Key key,
this.alignment = AlignmentDirectional.topStart,//如何对齐堆栈中未定位和部分定位的子元素。
this.textDirection,
this.fit = StackFit.loose,//约束方式,如何调整堆栈中未定位的子元素的大小。
enum StackFit {
从其父节点传递到堆栈的约束被解除。
例如,如果堆栈有约束,迫使它为350x600,那么这将允许堆栈的非定位子元素具有从0到350的任意宽度和从0到600的任意高度。
constraints.
loose,
从父节点传递给堆栈的约束被收紧到允许的最大大小。
例如,如果堆栈具有宽在范围内的松散约束10到100,高度在0到600之间,那么堆栈的非定位子元素的大小都是100像素宽,600高。
expand,
从父堆栈传递到堆栈的约束将不加修改地传递给未定位的子堆栈。
例如,如果[Stack]是[Expanded]的[Row]子堆栈,则水平约束将是紧的,而垂直约束将是松的。
passthrough,
}
this.overflow = Overflow.clip,//子元素大小超出父容器,溢出修剪方式。默认溢出部分裁剪掉
List<Widget> children = const <Widget>[],
})
*/
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
// TODO: implement build
return MaterialApp(
title: "Flutter Demo",
debugShowCheckedModeBanner: false,
home: Scaffold(
appBar: AppBar(
title: Text("Stack Sample"),
),
body: Column(
children: <Widget>[
Expanded(//均分布局
child: ConstrainedBox(//解除撑满水平方向限制
constraints: BoxConstraints.expand(),
child: Stack(
alignment: Alignment.center,
children: <Widget>[
Positioned(
left: 18.0,
child: Text("I am 不求人"),
),
Container(
child: Text("Hello world",
style: TextStyle(color: Colors.white)),
color: Colors.red,
),
Positioned(
top: 18.0,
child: Text("Your friend"),
),
],
),
),
),
Expanded(
child: Container(
padding: EdgeInsets.all(5),
color: Colors.greenAccent,
child: Stack(
alignment: Alignment.center,
fit: StackFit.expand,
children: <Widget>[
Positioned(
left: 18.0,
child: Text("I am 不求人"),
),
Container(
//没有被Positioned约束,撑满父容器,"I am 不求人" 被遮挡了
child: Text("Hello world",
style: TextStyle(color: Colors.white)),
color: Colors.red,
),
Positioned(
top: 18.0,
child: Text("Your friend"),
),
],
),
),
),
Container(
padding: EdgeInsets.all(5),
width: 150.0,
height: 150.0,
color: Colors.purple,
child: Stack(
alignment: Alignment.center,
children: <Widget>[
Container(
//overflow = Overflow.clip,父容器大小150,子元素多余的部分被裁剪掉了
width: 200,
height: 200,
color: Colors.red,
),
Container(
width: 90,
height: 90,
color: Colors.green,
),
Container(
width: 80,
height: 80,
color: Colors.blue,
),
Positioned(
left: 5.0,
child: Text("Your friend"),
),
],
),
)
],
)),
);
}
}