You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Flutter中如何为TextField文本添加末尾省略号?

解决TextField文本过长显示省略号的问题

要实现TextField中文本超出范围时末尾显示省略号,只需在TextField的样式配置中添加溢出规则,并配合行数限制即可,具体修改如下:

关键修改点

  • 在TextField的style里添加overflow: TextOverflow.ellipsis,指定超出部分显示省略号
  • 设置maxLines: 1(单行展示场景),若需多行则设置对应行数或null(自动换行),确保文本不会超出容器

修改后的完整代码

Widget build(BuildContext context) {
  return SizedBox(
    height: 58,
    child: Card(
      shape: RoundedRectangleBorder(
        borderRadius: BorderRadius.circular(8),
      ),
      child: TextField(
        // 新增行数限制与文本溢出处理
        maxLines: 1,
        style: constants.Styles.smallTextStyleWhite.copyWith(
          overflow: TextOverflow.ellipsis,
        ),
        controller: controller,
        onChanged: (v) {
          if (onChange != null) onChange!(v);
        },
        keyboardType: type,
        obscureText: isObscureText ?? false,
        decoration: InputDecoration(
          isDense: true,
          border: InputBorder.none,
          suffixIcon: suffixIcon ?? suffixPassIcon,
          enabled: enabled,
          errorText: error,
          contentPadding: const EdgeInsets.only(left: 8, top: 8, right: 8, bottom: 0),
          labelText: hint,
          labelStyle: constants.Styles.textFieldLabelLightGreyStyle,
        ),
      ),
    ),
  );
}

补充说明

  • 若需支持多行文本,可将maxLines设为null(自动换行)或具体数值(如maxLines: 2),此时省略号会显示在最后一行末尾
  • 通过copyWith覆写overflow属性,不会修改原样式smallTextStyleWhite的全局配置,避免影响其他组件使用

内容的提问来源于stack exchange,提问作者Max

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.17 07:55:20