如何在Flutter中隐藏TextField底部的字母计数器

182

在此输入图像描述

我遇到了一个小问题。如您所见,在Flutter中我将TextField的maxLength设置为1,但我无法隐藏文本计数器的底部标签。

22个回答

361

在使用 maxLength 属性时,想要隐藏 TextFieldTextFormField 组件的计数值,请尝试以下方法:

TextField(
  decoration: InputDecoration(
    hintText: "Email",
    counterText: "",
  ),
  maxLength: 40,
),
在这里,我已经在InputDecoration属性中设置了counterText属性,并将其设为空值。希望它能帮助到您。

9
如果你只是想将其隐藏起来,那么这很好,但它仍然存在并且经常会占据空间,导致文本框不平均。 用TextField( inputFormatters: [LengthLimitingTextInputFormatter(mMaxLength)] )替换maxLength就可以解决问题,但需要在文件中添加额外的库。 - Joel Broström
1
这个程序是可以工作的,但是 counterText 占用了空间高度并影响了用户界面。 - Farhana Naaz Ansari
18
对我来说,没有保留空白区域,它被移除了,运行最新版本的Flutter会有帮助吗? - voytez
@FarhanaNaazAnsari,还要设置您的helperText = ' '。如果不起作用,请将其包装在容器中。 - Pius T.K

164

这是恰当的方法,它将防止文本字段下方出现额外空白,并避免增加设置空小部件所需的额外代码。

您可以在 TextField 中使用输入格式化程序。

以下是:

    inputFormatters:[
      LengthLimitingTextInputFormatter(1),
    ]

谢谢!


8
它能正常运行,但需要在文件中导入额外的库:import 'package:flutter/services.dart'; - Joel Broström
我曾尝试使用 InputDecoration.collapsed 方法,但是它并没有起作用。然而,user10481267的回答却有效。 - Tokenyet
2
很明显,为了使其正常工作,必须删除 maxLength 参数。 - flomaster

48

您可以使用InputDecoration来隐藏字母计数器。

TextFormField(
   decoration: InputDecoration(
     labelText: "username",
     counterStyle: TextStyle(height: double.minPositive,),
     counterText: ""
)

问题与TextField有关,而不是TextFormField。感谢您在TextFormField方面的建议。 - Kamlesh
1
答案是TextField(decoration:InputDecoration(counterText:'',)) - Kamlesh
1
你刚刚救了我一命。祝你长命百岁,朋友。 - undefined

43

textfield修饰中加入counterText: ''可以隐藏计数器。这将仅显示一个空字符串。


2
IT 仍然占据计数器空间。 - user3808307

37

只需将计数器设置为 Offstage() 即可解决问题。

TextField(
    maxLines: 1,
    decoration: InputDecoration(
      counter: Offstage(),
    ),
),

1
这个解决方案仍然会影响GUI(将输入文本移动到超过最大长度计数器的上方)。最好的解决方案(至少对于我的用例)是“counterText =”“”解决方案。 - SilSur

23

你可以做:

TextField(
   maxLength: 10,
   buildCounter: (BuildContext context, { int currentLength, int maxLength, bool isFocused }) => null,
)

17

大多数答案似乎都可以运行。另一种方法是使用收缩的SizeBox来分配计数器。

TextField(decoration: InputDecoration(
    hintText: "Email",
    counter: SizedBox.shrink()
),
  maxLength: 40,
),

没有导入任何新库,这对我很有效! - blessing dickson
你为缩小尺寸的框添加了任何值吗? - Kevin Nzioka

12
counterText: "",添加到InputDecoration。

counterText示例图片

TextField(
    decoration: InputDecoration(
        counterText: "",
    ),
    maxLength: 10,
),

11
这就解决了我的问题!
TextField(
   decoration: InputDecoration(
     labelText: "Table Number",
     counterText: ""
)

9
只需将 buildCounter 设置为 null。
这是一个回调函数,用于生成一个自定义的 [InputDecorator.counter] 小部件。
TextField(
   maxLength: (some length),
   buildCounter: (BuildContext context, {int currentLength, int maxLength, bool isFocused}) => null,
);

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接