flutter - 无论如何在颤动中改变textlengthlimit指标的属性?
问题描述
我只想在文本表单字段中获取输入文本计数器和最大长度
TextFormField(
controller: newusrname, //u can ignore this controller
maxLength: 30, //this is the limit i have set
decoration: InputDecoration(
prefixIcon: Icon(Icons.account_box),
labelText: "Username",
labelStyle: TextStyle(
fontSize: 20.0,
),
border: OutlineInputBorder(
borderRadius: BorderRadius.circular(8.0)),
),
),
解决方案
试试这个
TextEditingController _controller = new TextEditingController();
String text = ""; // empty string to carry what was there before it
int maxLength = 30;
TextFormField(
controller: _controller,
decoration: InputDecoration(
prefixIcon: Icon(Icons.account_box),
labelText: "Username",
suffix: Text("${_controller.text.length}/$maxLength"),
labelStyle: TextStyle(
fontSize: 20.0,
),
border: OutlineInputBorder(
borderRadius: BorderRadius.circular(8.0)),
),
onChanged: (String newVal) {
setState(() {
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;
}
});
},
),