3

Container颤振的小部件中,

height给它一个固定的和为财产width 提供它有什么区别?BoxConstraintsconstraints.

它是提供宽度+高度还是约束?可以同时提供吗?有什么不同?

我还查看了官方文档,其中提到了Container小部件,并且在名为布局行为的标题下,他们提到了当宽度和高度以及约束的不同组合时会发生什么?(但我不明白它们有何不同)

4

1 回答 1

3

TLDR:他们做同样的事情

长答案: 如果您查看Container' 代码,您会发现您提供的widthheight实际上变成了BoxConstraints. Container将使用它BoxConstraints来设置其约束。这是 2021 年 10 月Container的构造函数片段:

  Container({
    Key? key,
    this.alignment,
    this.padding,
    this.color,
    this.decoration,
    this.foregroundDecoration,
    double? width,
    double? height,
    BoxConstraints? constraints,
    this.margin,
    this.transform,
    this.transformAlignment,
    this.child,
    this.clipBehavior = Clip.none,
  }) : // *Removed the asserts it made to make this snippet shorter
       // Important part is here
       constraints =
        (width != null || height != null)
          ? constraints?.tighten(width: width, height: height)
            ?? BoxConstraints.tightFor(width: width, height: height)
          : constraints,
       super(key: key);

这是Container's build 方法的一部分:

// Parts of the code removed to shorten snippet
if (constraints != null)
  current = ConstrainedBox(constraints: constraints!, child: current);
// Parts of the code removed to shorten snippet
return current!;
于 2021-10-19T14:19:13.493 回答