层叠布局 Stack

Stack

Stack 允许子组件堆叠

https://api.flutter.dev/flutter/widgets/Stack-class.html

  • 定义
Stack({

	Key key,

	// 对齐方式,默认是左上角(topStart)
	this.alignment = AlignmentDirectional.topStart,

	// 对齐方向
	this.textDirection,

	// 定义如何设置无定位子元素尺寸,默认为loose
	this.fit = StackFit.loose,

  // 对超出 Stack 显示空间的部分如何剪裁
  this.clipBehavior = Clip.hardEdge,

	// 子元素
	List<Widget> children = const <Widget>[],

})

Positioned

根据 Stack 的四个角来确定子组件的位置

  • 定义
const Positioned({

	Key key,

	this.left, // 上下左右位置
	this.top,
	this.right,
	this.bottom,

	this.width, // 宽高
	this.height,

	 Widget child,

})

示例

代码

import 'package:flutter/material.dart';

class StackPage extends StatelessWidget {
  const StackPage({Key? key}) : super(key: key);

  
  Widget build(BuildContext context) {
    return Scaffold(
      body: SizedBox(
        width: 300,
        height: 300,
        child: Stack(
          // 居中对齐
          alignment: Alignment.center,
          // 子元素溢出, none 不裁剪
          clipBehavior: Clip.none,
          // 子元素层叠放
          children: [
            // 三个色块
            Container(
              width: 300,
              height: 300,
              color: Colors.amber,
            ),
            Container(
              width: 200,
              height: 200,
              color: Colors.blue,
            ),
            Container(
              width: 100,
              height: 100,
              color: Colors.green,
            ),
            // 绝对定位
            const Positioned(
              left: 0,
              bottom: -50,
              child: FlutterLogo(size: 100),
            ),
          ],
        ),
      ),
    );
  }
}

输出

image-20220620152434274
Last Updated:
Contributors: ducafecat