【问题标题】:Container size depending on his content (text)容器大小取决于他的内容(文本)
【发布时间】:2021-08-18 01:04:55
【问题描述】:

我希望我的容器根据其内容(在本例中为文本)具有不同的大小,如果一个用户编写较长的文本,容器会更大,如果另一个用户编写较短的文本,容器会更小。

有可能吗?如果没有,还有其他方法吗?

谢谢

This is what I want to achieve (it's a screenshot of Samsung note app)

【问题讨论】:

  • 你自己试过能不能显示你的代码?
  • 是的,我尝试了多次,但总是以失败告终,但由于下面的答案,它终于可以工作了。

标签: flutter flutter-container flutter-card


【解决方案1】:

您不需要将widthheight 分配给Container,因此它将根据child 调整大小:


Container(
     color: Colors.red,
     child: const Text("Hi there111"),
)

如果您想控制最大宽度和最大高度,您将使用Containerconstraints 字段


Container(
      color: Colors.red,
      constraints: const BoxConstraints(
          maxWidth: 200,
      ),
      child: const Text("Hi there11122222222"),
)

当然你也可以在BoxConstraints 中给它minWidthminHeight

maxWidth下的结果

文本太长以至于超出maxWidth 的范围时的结果,在这种情况下高度会自动调整大小:

您还可以添加填充以获得更好的外观:


Container(
    padding: EdgeInsets.all(20),
    color: Colors.red,
    constraints: const BoxConstraints(
      maxWidth: 200,
    ),
    child: const Text("Hi there11122222222222222222"),
)

但是对于其他类型的小部件,除了Text,如果像这样用FittedBox 包裹它们会更安全,注意Text 小部件


Container(
    padding: EdgeInsets.all(20),
    color: Colors.red,
    constraints: const BoxConstraints(
      maxWidth: 200,
    ),
    child: FittedBox(
       fit: BoxFit.fill,
       child: const Text("asfasfasfasfasf")
    ),

)

【讨论】:

  • 感谢小伙伴花时间解释清楚
  • 很高兴为您提供帮助
猜你喜欢
  • 1970-01-01
  • 2022-06-10
  • 1970-01-01
  • 2013-06-14
  • 2020-02-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多