问题描述
我希望我的容器根据其内容(在本例中为文本)具有不同的大小,如果一个用户编写较长的文本,则容器会更大,如果另一个用户编写较短的文本,则容器会较小。
有可能吗?如果没有,还有其他方法吗?
谢谢
This is what I want to achieve (it's a screenshot of Samsung note app)
解决方法
您不需要将 width
或 height
分配给 Container
,因此它会根据 child
调整大小:
Container(
color: Colors.red,child: const Text("Hi there111"),)
如果您想控制最大宽度和最大高度,您将使用 Container
的 constraints
字段
Container(
color: Colors.red,constraints: const BoxConstraints(
maxWidth: 200,),child: const Text("Hi there11122222222"),)
当然,您可以在 minWidth
中给它 minHeight
和 BoxConstraints
。
当您低于 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),child: FittedBox(
fit: BoxFit.fill,child: const Text("asfasfasfasfasf")
),)