如何限制文本字段的大小?
问题描述:
TextField小部件似乎没有“限制”属性来限制可键入的字符数。我如何强制在TextField Widget中只能输入一定数量的字符作为输入。我试着看看装修房产,并可能在某种程度上设置了限制,但那似乎也不起作用。我应该使用不同的小工具吗?如何限制文本字段的大小?
答
我不得不添加一个额外的片段,以什么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;
}
}
);
答
您可以使用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,
onChange: (String newVal) {
if(newVal.length <= maxLength){
text = newVal;
}else{
_controller.text = text;
}
}
)
我能够控制文本字段留指引的范围内,因为如果它曾经越过它,它会恢复到什么是最后的类型之前。