【问题标题】:How can I layout a widget based on the size of its child?如何根据子组件的大小来布局小部件?
【发布时间】:2019-10-11 08:35:38
【问题描述】:

我正在尝试构建一个宽度 =(其子宽度 + 10)的容器。孩子也是一个带有 Text 小部件的容器,它可以有不同的文本内容。

我试图将 child 提取到 Statefull 小部件,但未能公开其大小。

这是我的最小代码:

  final GlobalKey _childKey = GlobalKey();

  _getChildWidth() {
    final Size size = _childKey.currentContext.size;
    final width = size.width;
    return width;
  }

  Widget child = Container(
    key: _keyChild,
    child: Text("text here"),
  );

  Widget parent = Container(
    width: _getChildWidth + 10,
    child: child,
  );

【问题讨论】:

  • 你能添加一个你的 UI 必须如何的图像/原型吗?也许有更好的方法来做你想做的事......
  • @siega dribbble.com/shots/2704939-Messages 聊天气泡就是一个很好的例子。父容器的宽度基于其子容器的文本长度。

标签: flutter flutter-layout


【解决方案1】:

一种选择是创建一个容器,放置一个水平填充属性 5(左 5 + 右 5)和一个 Text 子项,如下所示:

  Container(
      padding: EdgeInsets.symmetric(horizontal: 5.0),
      child: Text('text here'),
  );

【讨论】:

    【解决方案2】:

    听起来您正在寻找Padding 小部件,尽管Container 也有一个padding 属性:https://api.flutter.dev/flutter/widgets/Container/padding.html

    【讨论】:

      猜你喜欢
      • 2017-05-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-03-11
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多