【问题标题】:Nested container not respecting size constraints嵌套容器不遵守大小限制
【发布时间】:2019-10-08 22:42:10
【问题描述】:

我有以下代码:

  @override
  Widget build(BuildContext context) => Container(
        height: MediaQuery.of(context).size.height * 0.5,
        width: MediaQuery.of(context).size.width,
        color: Colors.green.withOpacity(0.3),
        child: Container(
          alignment: Alignment.center,
          height: MediaQuery.of(context).size.height * 0.25,
          color: Colors.red.withOpacity(0.3),
        ),
      )

我希望看到一个红色矩形占据屏幕的一半,并在一个绿色矩形内居中占据屏幕的四分之一。但相反,绿色的跨越了整个一半(与红色的大小相同)。

为什么会这样? 如何在不使用 Stack 的情况下获得预期的结果?

有关更多上下文,我正在尝试解决 GestureDetector 在使用 Transform 小部件翻译后无法正确响应的问题: https://github.com/flutter/flutter/issues/27587

编辑:

睡了一夜后,达到预期效果的解决方案很容易实现,我在内部容器中添加了一些边距,如下所示:

  @override
  Widget build(BuildContext context) => Container(
        height: MediaQuery.of(context).size.height * 0.5,
        width: MediaQuery.of(context).size.width,
        color: Colors.green.withOpacity(0.3),
        child: Container(
          margin: EdgeInsets.symmetric(vertical: MediaQuery.of(context).size.height * 0.25 * 0.5),
          color: Colors.red.withOpacity(0.3),
        ),
      );

但我更感兴趣的是了解为什么第一个代码没有按预期工作。我阅读了 Container 小部件的源代码,但找不到任何明显的原因。有人知道吗?

编辑 2:

@Pablo Barrera Answers 给了我尝试将对齐添加到第一个容器的想法(这确实应该是这样)。

它还使第二个容器具有预期的大小,这是出乎意料的。仍然很想知道这是否有合理的解释。

  @override
  Widget build(BuildContext context) => Container(
        height: MediaQuery.of(context).size.height * 0.5,
        width: MediaQuery.of(context).size.width,
        alignment: Alignment.center,
        color: Colors.green.withOpacity(0.3),
        child: Container(
          height: MediaQuery.of(context).size.height * 0.25,
          color: Colors.red.withOpacity(0.3),
        ),
      );

【问题讨论】:

  • 关于您的编辑 2:当向根容器添加 'alignment: Alignment.center' 时,在幕后它使用 Align 小部件包装它的孩子,因此不再需要 Wrap 小部件,因为子容器不会尝试扩展以适应根容器(我用这个更新了我的答案)

标签: flutter


【解决方案1】:

你可以像这样使用 Wrap 小部件:

@override
Widget build(BuildContext context) => Container(
  alignment: Alignment.center,
  height: MediaQuery.of(context).size.height * 0.5,
  width: MediaQuery.of(context).size.width,
  color: Colors.green.withOpacity(0.3),
  child: Wrap(
    children: <Widget>[
      Container(
        height: MediaQuery.of(context).size.height * 0.25,
        color: Colors.red.withOpacity(0.3),
      ),
    ],
  )
)

编辑: 将 'alignment: Alignment.center' 添加到根容器时,它会在后台使用 Align 小部件包装它的子容器,因此不再需要 Wrap 小部件,因为子容器不会尝试扩展以适应根容器

【讨论】:

  • 谢谢,这确实会强制遵守尺寸限制,但不会使框居中。
  • 你应该添加对齐:Alignment.center 到根容器,我编辑了我的答案
猜你喜欢
  • 1970-01-01
  • 2020-09-04
  • 1970-01-01
  • 2023-03-24
  • 1970-01-01
  • 2021-01-08
  • 2021-02-03
  • 1970-01-01
  • 2020-05-26
相关资源
最近更新 更多