I'm implementing two simple dialogs to allow the user to edit two settings in my app. They're very similar, as you can see from the code.
First one, used to input a 5-digit number (I convert the String
into a number later):
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();
})
],
);
});
Second dialog, a generic text input:
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();
})
],
);
});
The first dialog works perfectly: when needed, it pops up with the field already focused, the keyboard shows only numbers, and the input is limited automatically at length 5, as expected. So, when I needed the user to input a limited text string, I simply duplicated the code, changing just the length.
Everything seemed to work fine, so at first I didn't even bother to check if the maxLength
was enforced: I only discovered, much later, that the second dialog allows the user to exceed the maximum length, although it correctly changed the color of the hint and the underline to red, to let the user know that something was wrong.
I know I can easily set up a work-around for this, like truncating the String after the user confirms the input, but the question is more about WHY the two dialogs act differently than how to solve this.
The question has become irrelevant, since the maxLengthEnforced argument has been deprecated and has been replaced with maxLengthEnforcement, which has a more complex behaviour.