在溢出时缩小 TextField 的字体大小 - Flutter

问题描述 投票:0回答:4

我希望 TextField 内容的字体大小在达到 TextField 的特定宽度时缩小。我尝试了一些解决方案,例如使用文本跨度计算文本宽度,但我希望有一个性能更高的解决方案。

非常感谢任何帮助。

flutter dart textfield
4个回答
0
投票

auto_size_text 包仅适用于常规文本小部件。

另一方面,

auto_size_text_field会给你你想要的。


0
投票

用 FittedBox 小部件包裹它

FittedBox(
 fit: BoxFit.scaleDown,
 child: Text(...)
 )

0
投票

这个解决方案对我有用:

SizedBox(
    width: desiredWidth,
    height: desiredHeight,
    child: FittedBox(
        fit: BoxFit.scaleDown,
        child: IntrinsicWidth(
            child: ConstrainedBox(
                constraints: BoxConstraints(
                    minWidth: desiredWidth,
                    minHeight: desiredHeight,
                ),
                child: TextField(
                    ...
                ),
            ),
        ),
    ),
)

内部

ConstrainedBox
不是必需的,但是,如果没有它,当
TextField
为空时,
IntrinsicWidth
会缩小它,创建一个非常小的目标。

在我的项目中,我注意到根据我使用的

BoxFit
类型存在一些细微的差异,因此您可以根据您的需要进行调整。

一些缺点:

  • 没有下限,因此文本将继续缩小到超出可读范围
  • 它不会跟踪缩放系数,因此如果您将其用于两个
    TextField
    ,它们的字体大小可能会不匹配

-1
投票

最好的方法是使用包自动调整文本大小

https://pub.dev/packages/auto_size_text

检查:

AutoSizeText(
  'My Text',
  style: TextStyle(fontSize: 30),
  minFontSize: 18,
  maxLines: 4,
  overflow: TextOverflow.ellipsis,
)
© www.soinside.com 2019 - 2024. All rights reserved.