flutter 布局限制容器wdiget ConstrainedBox和SizedBox

1.描述

ConstrainedBox用于对子widget添加额外的约束

SizedBox用于给子widget指定固定的宽高,实际上SizedBox只是ConstrainedBox的一个定制

2.属性

const BoxConstraints({

  this.minWidth = 0.0, //最小宽度

  this.maxWidth = double.infinity, //最大宽度

  this.minHeight = 0.0, //最小高度

  this.maxHeight = double.infinity //最大高度

})

3.示例

import 'package:flutter/material.dart';

class MyCons extends StatelessWidget{

  Widget _size(){
    //SizedBox只是ConstrainedBox的一个定制
    //等价于 BoxConstraints(minHeight: 80.0,maxHeight: 80.0,minWidth: 80.0,maxWidth: 80.0)
    return SizedBox(height: 80,width: 80,child: Container(
        height: 10.0, //不起作用,最小是80
        decoration: BoxDecoration(
          color: Colors.cyanAccent
        ),
      ));
  }

  Widget build(BuildContext context){
    return Scaffold(
      appBar: AppBar(centerTitle: true,title: Text("Constraint"),),
      body: Column(children: [
        InnerCons(),
        _size()
      ],),
    );
  }
}

class InnerCons extends StatelessWidget{
  @override
  Widget build(BuildContext context) {
    // 添加约束的容器
    return ConstrainedBox(
      constraints: BoxConstraints(
        minHeight: 60.0,  //最小60
        maxHeight: 80.0,
        minWidth: double.infinity
      ),
      child: Container(
        height: 10.0, //不起作用,最小是60
        decoration: BoxDecoration(
          color: Colors.blueAccent
        ),
      ),
    );
  }

}

flutter 布局限制容器wdiget ConstrainedBox和SizedBox_第1张图片

4.如果某一个widget有多个父ConstrainedBox限制,发现有多重限制时,对于minWidth和minHeight来说,是取父子中相应数值较大的

ConstrainedBox(
    constraints: BoxConstraints(minWidth: 60.0, minHeight: 60.0), //父
    child: ConstrainedBox(
      constraints: BoxConstraints(minWidth: 90.0, minHeight: 20.0),//子
      child: redBox,
    )
)

// 最终显示效果是宽90,高60


ConstrainedBox(
    constraints: BoxConstraints(minWidth: 90.0, minHeight: 20.0),
    child: ConstrainedBox(
      constraints: BoxConstraints(minWidth: 60.0, minHeight: 60.0),
      child: redBox,
    )
)

//最终的显示效果仍然是90,高60

5.UnconstrainedBox

UnconstrainedBox不会对子Widget产生任何限制,它允许其子Widget按照其本身大小绘制。一般情况下,我们会很少直接使用此widget

ConstrainedBox(

    constraints: BoxConstraints(minWidth: 60.0, minHeight: 100.0),  //父

    child: UnconstrainedBox( //“去除”父级限制

      child: ConstrainedBox(

        constraints: BoxConstraints(minWidth: 90.0, minHeight: 20.0),//子

        child: redBox,
      ),
    )

)

flutter 布局限制容器wdiget ConstrainedBox和SizedBox_第2张图片

UnconstrainedBox对父限制的“去除”并非是真正的去除,上面例子中虽然红色区域大小是90×20,但上方仍然有80的空白空间。也就是说父限制的minHeight(100.0)仍然是生效的,只不过它不影响最终子元素redBox的大小,但仍然还是占有相应的空间

可以通过UnconstrainedBox来去除父元素(一般是系统默认的组件)

 

你可能感兴趣的:(flutter)