【问题标题】:Giving a fixed width and height to a container vs providing constraints via a BoxConstraints class为容器提供固定的宽度和高度与通过 BoxConstraints 类提供约束
【发布时间】:2021-12-06 11:25:44
【问题描述】:

在flutter中的Container小部件中,

给它一个固定的heightwidth 和为constraints 属性提供BoxConstraints 有什么区别?

是提供 width + height 还是 constraints?可以同时提供吗?有什么区别?

我还查看了 official docs ,它指的是 Container 小部件,并在其中,在名为 Layout Behavior 的标题下,他们提到了当宽度和高度以及约束的不同组合时会发生什么做? (但我不明白它们有何不同)

【问题讨论】:

    标签: flutter flutter-layout flutter-web flutter-animation flutter-container


    【解决方案1】:

    TLDR:他们做同样的事情

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

      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的构建方法的一部分:

    // 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!;
    

    【讨论】:

    • BoxConstrains 中,有名为minWidthmaxWidth 等的属性......对吗?但是当给Container 一个width 时,我们只提供一个width 对吗?如果它们都相同,为什么我们只能设置一个width 而在BoxConstraints 中存在两个名为minWidthmaxWidth 的属性? (我不清楚)
    • @gfit21x 为了简单起见,他们添加了宽度和高度属性。大多数时候,不需要设置任何最小和最大宽度。使用BoxConstraint 会增加我们为设置容器的宽度和高度而必须输入的代码量。
    • @gfit21x 当您设置height: 20 时,它会转换为minHeight: 20, maxHeight: 20(严格约束)。
    • 我现在有点困惑,因为我正在和一个我认识的人打电话,当我问他同样的问题时,他说“height + width 设置父小部件的尺寸,而constraints 告诉子小部件它们应该如何定位”....所以尽管答案提到它们是,但它们并不完全相同? ?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-01-25
    • 2019-07-12
    • 2019-01-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多