【发布时间】:2020-10-14 14:43:50
【问题描述】:
我正在实现两个简单的对话框,以允许用户在我的应用程序中编辑两个设置。从代码中可以看出,它们非常相似。
第一个,用于输入一个5位数字(我后面把String转成数字):
var tfController = TextEditingController();
String newPort = await showDialog<String>(
context: context,
builder: (BuildContext context) {
return AlertDialog(
content: Center(
heightFactor: 1,
child: TextField(
controller: tfController,
keyboardType: TextInputType.number,
maxLength: 5,
autofocus: true,
decoration: InputDecoration(labelText: "Insert number:"),
onEditingComplete: () {
Navigator.of(context).pop(tfController.text);
},
)),
actions: [
FlatButton(
child: Icon(Icons.done),
onPressed: () {
Navigator.of(context).pop(tfController.text);
},
),
FlatButton(
child: Icon(Icons.clear),
onPressed: () {
Navigator.of(context).pop();
})
],
);
});
第二个对话框,一个通用的文本输入:
var tfController = TextEditingController();
String newHeader = await showDialog<String>(
context: context,
builder: (BuildContext context) {
return AlertDialog(
content: Center(
heightFactor: 1,
child: TextField(
controller: tfController,
keyboardType: TextInputType.text,
maxLength: 30,
maxLengthEnforced: true, //added later even if it's true by default, doesn't change anything
autofocus: true,
decoration: InputDecoration(labelText: "Insert text:"),
onEditingComplete: () {
Navigator.of(context).pop(tfController.text);
},
)),
actions: [
FlatButton(
child: Icon(Icons.done),
onPressed: () {
Navigator.of(context).pop(tfController.text);
},
),
FlatButton(
child: Icon(Icons.clear),
onPressed: () {
Navigator.of(context).pop();
})
],
);
});
第一个对话框完美地工作:当需要时,它会弹出已经聚焦的字段,键盘只显示数字,并且输入自动限制为长度 5,正如预期的那样。因此,当我需要用户输入有限的文本字符串时,我只是复制了代码,只更改了长度。
一切似乎都运行良好,所以起初我什至懒得检查maxLength 是否被强制执行:我才发现,很久以后,第二个对话框允许用户超过最大长度,尽管它正确地改变了提示的颜色和下划线为红色,让用户知道有问题。
我知道我可以很容易地为此设置一个解决方法,例如在用户确认输入后截断字符串,但问题更多是关于为什么这两个对话框的行为不同于如何解决这个问题强>.
【问题讨论】:
标签: flutter textfield maxlength