层叠布局

2022/11/23 Flutter布局

本文介绍Flutter的StackPositioned组件,详细介绍了组件的定义和用法。

# Stack

Stack 允许子组件堆叠;

  • 定义
    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>[],
    })
    
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18

# Positioned

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

  • 定义
    const Positioned({
      Key key,
    
      // 上下左右位置
      this.left, 
      this.top,
      this.right,
      this.bottom,
    
      // 宽高
      this.width, 
      this.height,
    
       Widget child,
    })
    
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15

# 示例

  • 代码
    import 'package:flutter/material.dart';
    
    void main(List<String> args) {
      runApp(const ModelBox());
    }
    
    
    class ModelBox extends StatelessWidget {
      const ModelBox({Key? key}): super(key: key);
    
      
      Widget build(BuildContext context) {
        return MaterialApp(
          home: Scaffold(
            appBar: AppBar(
              title: const Text('Box Model'),
            ),
            body: Stack(
              alignment: Alignment.center,
              // 裁剪
              clipBehavior: Clip.none,
              children: [
                Container(
                  width: 300,
                  height: 300,
                  color: Colors.deepPurpleAccent,
                ),
                Container(
                  width: 200,
                  height: 200,
                  color: Colors.cyan,
                ),
                Container(
                  width: 100,
                  height: 100,
                  color: Colors.amber[100],
                  child: const Text('datadatadatadatadata'),
                ),
                const Positioned(
                  left: 100,
                  top: 300,
                  child: FlutterLogo(
                    size: 100,
                  ),
                )
              ],
            )
          ),
        );
      }
    }
    
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
最后更新时间: 2022/11/29 10:38:11