Flutter之Stack
2022-12-08 本文已影响0人
没有了遇见
Stack:相对于其长方体边缘定位其子对象的小部件。类似于Android中的FrameLayout
如果您希望以简单的方式重叠多个子项,例如,有一些文本和图像,并用渐变和底部附加的按钮重叠,则该类非常有用。

1.构造方式
1.1 构造方法
Stack({
super.key,
this.alignment = AlignmentDirectional.topStart, 子控件位置
this.textDirection,
this.fit = StackFit.loose,
this.clipBehavior = Clip.hardEdge,
super.children, //子控件
}) : assert(clipBehavior != null);
- alignment : 指的是子Widget的对其方式,默认情况是以左上角为开始点
- it : Positioned 用来决定没有Positioned方式时候子Widget的大小,
- StackFit.loose 指的是子Widget 多大就多大,
- StackFit.expand使子Widget的大小和父组件一样大
- child :[] 子控件 子控件Positioned 控制控件位置
1.2 Positioned 一个控件,用于控制堆栈子级的位置。
Positioned widget 用于定位 Stack 的子 widget.
Positioned 仅用作 Stack 的直接(或后代)子部件。在 Positioned 到 Stack 的路径上,它只包含 StatelessWidget 或 StatefulWidget 小部件,不允许使用其他小部件(例如 RenderObjectWidget)。

left、top 、right、 bottom分别代表离Stack左、上、右、底四边的距离
width,height 是子布局的大小 (建议设置上)
- left 位于父布局的左边距离
- top 位于父布局的顶部距离
- bottom 位于父布局的底部距离
- right 位于父布局的右边距离
- width, 子布局的大小
- height,子布局的大小
const Positioned({
super.key,
this.left,
this.top,
this.right,
this.bottom,
this.width,
this.height,
required super.child,
})
2. Demo
import 'package:flutter/material.dart';
import 'HomeIcon.dart';
import 'IconContainer.dart';
class MyStack extends StatelessWidget {
const MyStack({super.key});
@override
Widget build(BuildContext context) {
var size = MediaQuery.of(context).size;
return Container(
alignment: Alignment.center,
height: size.height,
width: size.width,
decoration: const BoxDecoration(color: Colors.black12),
child: Stack(
alignment: Alignment.topCenter,
children: [
Positioned(
top: 0,
//配置的是字组件的宽高 不配置以 子组件大小为主
width: size.width,
height: 44,
child: SizedBox(
width: size.width,
height: 44,
child: Flex(
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
direction: Axis.horizontal,
children: [
Expanded(
flex: 1,
child: IconContainer(
HomeIcon.search,
myColor: Colors.black,
)),
Expanded(
flex: 1,
child: IconContainer(
HomeIcon.search,
myColor: Colors.black,
)),
],
),
),
),
const Positioned(top: 66, child: Text("1212124341")),
Positioned(
top: 100,
height: size.height,
width: size.width,
child: ListView(
children: const [
ListTile(
title: Text("测试头部"),
),
ListTile(
title: Text("测试"),
),
ListTile(
title: Text("测试"),
),
ListTile(
title: Text("测试"),
),
ListTile(
title: Text("测试"),
),
ListTile(
title: Text("测试"),
),
ListTile(
title: Text("测试"),
),
ListTile(
title: Text("测试"),
),
ListTile(
title: Text("测试"),
),
ListTile(
title: Text("测试"),
),
ListTile(
title: Text("测试"),
),
ListTile(
title: Text("测试"),
),
ListTile(
title: Text("测试"),
),
ListTile(
title: Text("测试"),
),
ListTile(
title: Text("测试"),
),
ListTile(
title: Text("测试"),
),
ListTile(
title: Text("测试"),
),
ListTile(
title: Text("测试"),
),
ListTile(
title: Text("测试"),
),
ListTile(
title: Text("测试"),
),
ListTile(
title: Text("测试"),
),
ListTile(
title: Text("测试"),
),
ListTile(
title: Text("测试"),
),
ListTile(
title: Text("尾部"),
),
],
)),
],
),
);
}
}
