Flutter问题记录 - TextField组件多行提示文本显示不全


前言

梳理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,
  ),
);

提示文本显示不全只显示一行:

screenshot1

问题分析

首先确定是不是因为没有设置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,再加上hintMaxLinesnull,这对于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,
  ),
);

重新运行,一切正常🎉!

screenshot2

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

screenshot3

解决方案

TextField组件的提示文本hintText不限制行数时,需要通过hintStyle设置overflow属性,只要不是TextOverflow.ellipsis都可以。

最后

如果这篇文章对你有所帮助,请不要吝啬你的点赞👍加星🌟,谢谢~

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值