文章目录
- 前言
- 开发环境
- 问题描述
- 问题分析
- 解决方案
- 最后
前言
梳理Flutter项目的过程中发现还有一些遗留的TODO没处理,其中有一个和TextField组件相关。
开发环境
- Flutter: 3.10.1
- Dart: 3.0.1
问题描述
TextField组件设置maxLines: null不限制行数,同时设置多行提示文本hintText:
TextField(
maxLines: null,
decoration: InputDecoration(
hintText: 'Text that suggests what sort of input the field accepts.' * 5,
border: InputBorder.none,
),
);
提示文本显示不全只显示一行:

问题分析
首先确定是不是因为没有设置hintMaxLines属性的原因导致的问题:
TextField(
maxLines: null,
decoration: InputDecoration(
hintText: 'Text that suggests what sort of input the field accepts.' * 5,
hintMaxLines: null,
border: InputBorder.none,
),
);
重新运行还是显示不全。找到hintMaxLines的定义:
/// The maximum number of lines the [hintText] can occupy.
///
/// Defaults to the value of [TextField.maxLines] attribute.
///
/// This value is passed along to the [Text.maxLines] attribute
/// of the [Text] widget used to display the hint text. [TextOverflow.ellipsis] is
/// used to handle the overflow when it is limited to single line.
final int? hintMaxLines;
从文档注释看,确实不用设置hintMaxLines属性也可以,默认等于TextField组件的maxLines,相关代码位于_TextFieldState类的_getEffectiveDecoration方法。不过,文档中出现了TextOverflow.ellipsis,这难道和这篇文章Flutter问题记录 - Text组件设置不限行数无效的问题一样?可是这里并没有设置overflow的属性为TextOverflow.ellipsis。
继续找到使用hintMaxLines属性的位置,位于_InputDecoratorState类的build方法:
Widget build(BuildContext context) {
...
final String? hintText = decoration.hintText;
final Widget? hint = hintText == null
? null
: AnimatedOpacity(
opacity: (isEmpty && !_hasInlineLabel) ? 1.0 : 0.0,
duration: _kTransitionDuration,
curve: _kTransitionCurve,
child: Text(
hintText,
style: hintStyle,
textDirection: decoration.hintTextDirection,
overflow: hintStyle.overflow ?? TextOverflow.ellipsis,
textAlign: textAlign,
maxLines: decoration.hintMaxLines,
),
);
...
}
破案了,当没有设置hintStyle.overflow时,会默认设置为TextOverflow.ellipsis,再加上hintMaxLines为null,这对于Text组件来说,必会截断为一行,具体缘由请看Flutter问题记录 - Text组件设置不限行数无效。
原因找到了,那问题就好解决啦!加上overflow设置,只要不是TextOverflow.ellipsis都可以:
TextField(
maxLines: null,
decoration: InputDecoration(
hintText: 'Text that suggests what sort of input the field accepts.' * 5,
hintStyle: const TextStyle(overflow: TextOverflow.fade),
border: InputBorder.none,
),
);
重新运行,一切正常🎉!

这个遗留的TODO有点久远了,在我印象中当时好像还有其他问题解决不了。翻了翻Flutter框架的历史提交记录,果然现在的解决方法搁那时候也还是行不通的。那时候overflow是硬编码的,直到去年11月才改成现在这样,详见hintText TextOverflow:

解决方案
TextField组件的提示文本hintText不限制行数时,需要通过hintStyle设置overflow属性,只要不是TextOverflow.ellipsis都可以。
最后
如果这篇文章对你有所帮助,请不要吝啬你的点赞👍加星🌟,谢谢~



















