容器大小取决于他的内容文本

问题描述

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

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

谢谢

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

解决方法

您不需要将 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"),)

当然,您可以在 minWidth 中给它 minHeightBoxConstraints

当您低于 maxWidth

时的结果

enter image description here

当文本长度超过 maxWidth 时的结果,在这种情况下,高度会自动调整大小:

enter image description here

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


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

enter image description here

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


Container(
    padding: EdgeInsets.all(20),child: FittedBox(
       fit: BoxFit.fill,child: const Text("asfasfasfasfasf")
    ),)

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...