当我开始思考这两个组件时,我发现自己在争论为什么我应该 Select 一个而不是另一个.我脑海中浮现出几个问题:

  1. Container和SizedBox有什么区别?

  2. 我知道Container可以有其他参数,如填充或装饰,但如果我不使用这些参数,为什么要使用SizedBox而不是Container呢?

  3. 它们之间有性能差异吗?

推荐答案

小更新:When used for whitespace, there is now even a linter warning to prefer SizedBox instead of Container.主要优点似乎是SizedBox可以是const,甚至不会在运行时创建新实例.


多亏了开源的魔力,您不必猜太多.

Container基本上只是一个方便的小部件,它有时可以让你省go 嵌套其他4个小部件.如果将宽度/高度传递到Container:

       constraints =
        (width != null || height != null)
          ? constraints?.tighten(width: width, height: height)
            ?? BoxConstraints.tightFor(width: width, height: height)
          : constraints,

这将导致:

    if (constraints != null)
      current = ConstrainedBox(constraints: constraints, child: current);

而ConstrainedBox实际上与SizedBox几乎相同,只是更灵活.

SizedBox分可以做到:

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

  BoxConstraints get _additionalConstraints {
    return BoxConstraints.tightFor(width: width, height: height);
  }

实际上是一样的.如果宽度/高度仅使用Container,那么性能开销可能非常小.但你肯定无法测量它..但我还是推荐SizedBox,因为它更清晰.依我拙见

Flutter相关问答推荐

Cupertino Buttino SheetAction on按下可触发加载指示器,然后勾选并延迟

无法在GroupButton内部正确呈现

我不能通过第5步了解Flutter 翼Firebase教程

Flutter API请求BadState响应

FittedBox叠加技术在Flutter 中的应用

flatter_localizations错误在Null值上使用了Null判断运算符

Flutter:如何在现有布局之上显示圆角布局?

Flutter开发中,如何通过'nfc_manager'插件在Android设备上避免默认的New Tag Scanned弹出窗口?

通过在父窗口小部件功能上设置状态来浏览屏幕

使用 Play Integrity API 时,Firebase 电话身份验证问题缺少客户端标识符错误

Flutter blue plus 库,当try 从 esp32 驱动程序获取 PlatformException 时读取特性

提供者、存储库和服务之间有什么区别?

如何与 PostgreSQL 和外部网站交互 flutter apk?

如何在 SingleChildScrollView 小部件中管理自定义小部件状态

在flutter web中重新加载页面时保留一些状态数据的有效方法是什么?

try 为两个下拉值添加共享首选项,但在 Flutter 上显示错误断言失败:?

Flutter Web Responsiveness 效率不高

Flutter 上Denim blue colored颜色 的 colored颜色 矩阵代码是什么?

使用 hydrad_bloc 的预览包

如何从 Flutter 中的列表中提取 JSON?