美文网首页
4.2 容器类Widget-约束盒子ConstrainedBox

4.2 容器类Widget-约束盒子ConstrainedBox

作者: lltree | 来源:发表于2018-12-31 16:21 被阅读27次

ConstrainedBox和SizedBox都是通过RenderConstrainedBox来渲染的。SizedBox只是ConstrainedBox一个定制,本节把他们放在一起讨论。

ConstrainedBox

ConstrainedBox用于对齐子widget添加额外的约束
例如,如果你想让子widget的最小高度是80像素,你可以使用const BoxConstraints(minHeight: 80.0)作为子widget的约束。

class ConstrainedBox extends SingleChildRenderObjectWidget {

  ConstrainedBox({
    Key key,
    @required this.constraints,
    Widget child
  }) : assert(constraints != null),
       assert(constraints.debugAssertIsValid()),
       super(key: key, child: child);
}

constraints用于设置限制条件,它的定义如下:

const BoxConstraints({
  this.minWidth = 0.0, //最小宽度
  this.maxWidth = double.infinity, //最大宽度
  this.minHeight = 0.0, //最小高度
  this.maxHeight = double.infinity //最大高度
})

示例

我们先定义一个redBox,它是一个背景颜色为红色的盒子,不指定它的宽度和高度:

image.png
import 'package:flutter/material.dart';

void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
      
        primarySwatch: Colors.blue,
      ),
      home: MyHomePage(),
    );
  }
}
class MyHomePage extends StatelessWidget{

  @override
  Widget build(BuildContext context) {

    return Scaffold(
      appBar: AppBar(
        // Here we take the value from the MyHomePage object that was created by
        // the App.build method, and use it to set our appbar title.
        title: Text("测试Padding"),
      ),
      body: Align(
        alignment: Alignment.topLeft,
        // Center is a layout widget. It takes a single child and positions it
        // in the middle of the parent.
        child: ConstrainedBoxTest()
      ),
    );
  }
}

class ConstrainedBoxTest extends StatelessWidget{

    @override
    Widget build(BuildContext context){

      return ConstrainedBox(//创建一个约束盒子

        constraints:BoxConstraints(//约束规则

          minWidth: double.infinity,//最小宽度无限大
          minHeight: 50,//最小高度为50像素
        ),
        child: Container(
          height: 5,//指定子盒子高度为5

          //添加红色子盒子
          child: DecoratedBox(
            decoration: BoxDecoration(color: Colors.red),
          ),
        ),
      );
    }
}

SizedBox

SizedBox用于给子widget指定固定的宽高,如:

SizedBox(
  width: 80.0,
  height: 80.0,
  child: redBox
)

运行效果:

实际上SizedBox和只是ConstrainedBox一个定制,上面代码等价于:

ConstrainedBox(
  constraints: BoxConstraints.tightFor(width: 80.0,height: 80.0),
  child: redBox, 
)

而BoxConstraints.tightFor(width: 80.0,height: 80.0)等价于:

BoxConstraints(minHeight: 80.0,maxHeight: 80.0,minWidth: 80.0,maxWidth: 80.0)

而实际上ConstrainedBox和SizedBox都是通过RenderConstrainedBox来渲染的,我们可以看到ConstrainedBox和SizedBox的createRenderObject()方法都返回的是一个RenderConstrainedBox对象:

@override
RenderConstrainedBox createRenderObject(BuildContext context) {
  return new RenderConstrainedBox(
    additionalConstraints: ...,
  );
}

多重限制

如果某一个widget有多个父ConstrainedBox限制,那么最终会是哪个生效?我们看一个例子:

ConstrainedBox(
    constraints: BoxConstraints(minWidth: 60.0, minHeight: 60.0), //父
    child: ConstrainedBox(
      constraints: BoxConstraints(minWidth: 90.0, minHeight: 20.0),//子
      child: redBox,
    )
)
上面我们有父子两个ConstrainedBox,他们的限制条件不同,运行后效果如下:

最终显示效果是宽90,高60,也就是说是子ConstrainedBox的minWidth生效,而minHeight是父ConstrainedBox生效。单凭这个例子,我们还总结不出什么规律,我们将上例中父子限制条件换一下:

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

最终的显示效果仍然是90,高60,效果相同,但意义不同,因为此时minWidth生效的是父ConstrainedBox,而minHeight是子ConstrainedBox生效。

通过上面示例,我们发现

有多重限制时,对于minWidth和minHeight来说,是取父子中相应数值较大的。实际上,只有这样才能保证父限制与子限制不冲突。

![](https://img.haomeiwen.com/i2160098/daa70e0e288b9703.jpeg?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)
//测试多重盒子约束
class MutlConstrainedBoxTest extends StatelessWidget{

   @override
    Widget build(BuildContext context){
      return Column(

        children: <Widget>[

          Container(  //创建一个宽高60的参考盒子
            width: 60,
            height: 60,

            color: Colors.green,
          ),

          ConstrainedBox(//父盒子
            constraints: BoxConstraints(
              maxHeight: 60,
              maxWidth: 90
              
            ),

            child: ConstrainedBox(

              constraints: BoxConstraints(
                maxHeight: 90,
                maxWidth: 60
              ),
              child: Container(
                color: Colors.red,
              )
            ),
          )
        ],
      );
    }
}

有多重限制时,对于maxHeight和maxWidth来说,是取父子中相应数值较小的。

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,
      ),
    )
)

上面代码中,如果没有中间的UnconstrainedBox,那么根据上面所述的多重限制规则,那么最终将显示一个90×100的红色框。但是由于 UnconstrainedBox “去除”了父ConstrainedBox的限制,则最终会按照子ConstrainedBox的限制来绘制redBox,即90×20:

但是,UnconstrainedBox对父限制的“去除”并非是真正的去除,上面例子中虽然红色区域大小是90×20,但上方仍然有80的空白空间。也就是说父限制的minHeight(100.0)仍然是生效的,只不过它不影响最终子元素的大小,但仍然还是占有相应的空间,可以认为此时的父ConstrainedBox是作用于子ConstrainedBox上,而redBox只受子ConstrainedBox限制,这一点请读者务必注意。

那么有什么方法可以彻底去除父BoxConstraints的限制吗?答案是否定的!所以在此提示读者,在定义一个通用的widget时,如果对子widget指定限制时一定要注意,因为一旦指定限制条件,子widget如果要进行相关自定义大小时将可能非常困难,因为子widget在不更改父widget的代码的情况下无法彻底去除其限制条件。

相关文章

网友评论

      本文标题:4.2 容器类Widget-约束盒子ConstrainedBox

      本文链接:https://www.haomeiwen.com/subject/fdailqtx.html