我从API中检索一段文本.我想为它分配一定量的空间(比如一个宽度为300.0且高度为100.0的最大容器).有时,这段文本适合此容器,字体大小为30.0.在其他时候,除非我将文本大小设置为24.0,否则它将不适合.
有没有办法根据其父容器空间动态调整文本大小?
我已经构建了一个带有ConstrainedBox的Container,它允许我定义文本空间的最大大小.我还用LayoutBuilder包装了我的Text.我希望我可以检查文本空间的高度,并在此基础上确定如何调整文本大小.像这样:
Container(
child: ConstrainedBox(
constraints: BoxConstraints(
minWidth: 300.0,
maxWidth: 300.0,
minHeight: 30.0,
maxHeight: 100.0,
),
child: LayoutBuilder(
builder: (BuildContext context, BoxConstraints constraints) {
if (/* height is larger than 100.0? height is over the constraints? */) { return textWithSize24(); }
return textWithSize30();
}),
),
),
Run Code Online (Sandbox Code Playgroud)
如何确定"文本大小为30.0时文本占用的高度"?也许我正在接近这个错误的方式而我应该maxLines用来确定这个呢?但是我们怎么知道我们达到了更多maxLines?
另一种方法是使用我的String中的字符数来确定何时更改字体大小.这似乎是一种手册.
Container(
child: Padding(
padding: const EdgeInsets.symmetric(horizontal: 60),
child: Text(
// subCategoryName,
"This is a very Long Text takes more space",
textAlign: TextAlign.center,
maxLines: 2,
overflow: TextOverflow.fade,
style: Theme.of(context)
.textTheme
.headline3
.copyWith(color: Colors.white, fontSize: 32),
),
),
),
Run Code Online (Sandbox Code Playgroud)
我需要这条线最多为两行,如果文本变得更长,则像 FittedBox(使用 BoxFit.fitWidth)一样缩小尺寸
当我使用 FittedBox 时,它看起来像这样。但如果需要的话,我需要将其增加到 2 行。任何解决方案都会受到赞赏