Flutter:Stack组件的使用

980 阅读1分钟
  • 让children里面的子组件像纸一样堆叠起来,有点像PS里面的图层。用来对子组件进行定位布局
  • 属性
    • alignment: Alignment(0,0)/Alignment.center 控制children里面子组件的位置,也可以使用Alignment(x,y)来进行精确控制。 x、y的取值不限制范围
    • fit: StackFit.loose 默认值 StackFit.expend可选
    • loose让Stack容器自适应,
    • expend让Stack容器占满整个父容器,Stack容器内的子组件的宽高失去作用,全部占满整个父容器
    • 注意:Stack会选取子组件中最大的容器作为基准(也就是不动的那个)而不是children中的第一个组件
  • 缺点:无法为每个组件单独定位
    import 'package:flutter/material.dart';
    
    class Home extends StatelessWidget {
      @override
      Widget build(BuildContext context) {
        return Scaffold(
          appBar: AppBar(
            title: Text("首页"),
            centerTitle: true,
          ),
            body: HomeBody()
        );
      }
    }
    
    class  HomeBody extends StatefulWidget {
      @override
       _HomeBodyState createState() =>  _HomeBodyState();
    }
    
    class  _HomeBodyState extends State <HomeBody> {
    
      @override
      void initState() {
        // TODO: implement initState
        print("进入首页init");
        super.initState();
        // HttpRequest.request("https://api.douban.com/v2/user/:name");
      }
      @override
      Widget build(BuildContext context) {
        return Center(
              child: Container(
                width: 400,
                height:400,
                color: Colors.red,
                child: Stack(
                  // 作用:让children里面的子组件像纸一样堆叠起来 有点像PS里面的图层
                  // alignment控制children里面子组件的位置
                  // 也可以使用Alignment(x,y)来进行精确控制
                  // x、y的取值不限制范围 
                  // alignment: Alignment.center,
                  // 注意:Stack会选取子组件中最大的容器作为基准(也就是不动的那个)
                  // 而不是children中的第一个组件
                  fit: StackFit.expand,
                  overflow: Overflow.visible,
                  alignment: Alignment(0,0),
                  // clipBehavior: Clip.antiAlias,
                  children: [
                    Container(
                      width: 200,
                      height:200,
                      color: Color.fromRGBO(255, 0, 0, 0.3),
                    ),
                    //  Container(
                    //   width: 300,
                    //   height:300,
                    //   color: Colors.blue,
                    // ),
                    // Container(
                    //   width: 100,
                    //   height:100,
                    //   color: Color.fromRGBO(255, 255, 255, 0.5),
                    // ),
                    Text(
                      "这是一个文本",
                      style: TextStyle(
                        fontSize: 16,
                        fontWeight: FontWeight.w400,
    
                      ),
                    )
    
                  ],
                ),
              ),
            );
      }
    }