TextField小部件似乎没有“ limit”属性来限制可以键入的字符数。我如何强制只能在TextField小部件中提供一定数量的字符作为输入。我尝试查看装饰属性,并可能以某种方式设置限制,但这似乎也不起作用。我应该使用其他部件吗?
Upa*_*Jah 14
在Flutter中可以使用maxLength属性
https://docs.flutter.io/flutter/material/TextField/maxLength.html
只需添加maxLength: 45,
TextField的属性
Shy*_*hil 12
使用inputFormatters属性
例:
TextFormField(
inputFormatters: [
LengthLimitingTextInputFormatter(10),
]
)
Run Code Online (Sandbox Code Playgroud)
命名空间
import 'package:flutter/services.dart';
Run Code Online (Sandbox Code Playgroud)
您可以使用maxLength属性,并且仍可以通过将counterText设置为空字符串来隐藏底部的计数器文本。
new TextField(
maxLength: 10,
decoration: new InputDecoration(
counterText: '',
)
)
Run Code Online (Sandbox Code Playgroud)
您可以使用 TextEditingController 控制有关文本字段的所有内容。因此,如果您要将这些信息与 TextField 中的 onChanged 事件配对,您可以在其中执行您喜欢的任何逻辑。例如:
TextEditingController _controller = new TextEditingController();
String text = ""; // empty string to carry what was there before it onChanged
int maxLength = ...
...
new TextField(
controller: _controller,
onChanged: (String newVal) {
if(newVal.length <= maxLength){
text = newVal;
}else{
_controller.text = text;
}
}
)
Run Code Online (Sandbox Code Playgroud)
我能够控制文本字段以使其保持在准则范围内,因为如果它超出了准则,它将恢复到最后一个类型之前的状态。
您可以在输入格式化程序中设置 LengthLimitingTextInputFormatter
TextField(
keyboardType: TextInputType.number,
inputFormatters: [
LengthLimitingTextInputFormatter(n,), //n is maximum number of characters you want in textfield
],
),
Run Code Online (Sandbox Code Playgroud)
我不得不在 RSproute 提到的内容中添加一个额外的片段。完整代码在这里:
TextEditingController _controller = new TextEditingController();
String text = ""; // empty string to carry what was there before it
onChanged
int maxLength = ...
...
new TextField(
controller: _controller,
onChange: (String newVal) {
if(newVal.length <= maxLength){
text = newVal;
}else{
_controller.value = new TextEditingValue(
text: text,
selection: new TextSelection(
baseOffset: maxLength,
extentOffset: maxLength,
affinity: TextAffinity.downstream,
isDirectional: false
),
composing: new TextRange(
start: 0, end: maxLength
)
);
_controller.text = text;
}
}
);
Run Code Online (Sandbox Code Playgroud)
小智 7
在 1.25 版本中,这变得更加容易。maxLengthEnforced属性需要设置为 true。否则上面的响应将不起作用。
Container(
margin: EdgeInsets.only(right: 5),
child: SizedBox(
width: 70,
child: TextField(
keyboardType: TextInputType.number,
maxLengthEnforced: true,
maxLength: 2,
decoration: InputDecoration(
labelText: 'Hours',
counterText: '',
),
controller: hourField,
),
),
),
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
12423 次 |
最近记录: |