TextField小部件似乎没有“限制”属性来限制可以键入的字符数。我如何强制只能在TextField小部件中提供一定数量的字符作为输入。我尝试查看装饰属性,并可能以某种方式设置限制,但这似乎也不起作用。我应该使用其他部件吗?
我必须在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; } } );