While the inputFormatters is realy well explained here and works like a charm I want to let the user know about what happened to his input. A simple snackBar or other dialog should be shown that prompts the user: "Your code has been trimmed because of unallowed signs. You are only allowed to enter numbers and letters!"
my example code shows the limitation to numbers and letters:
TextFormField( inputFormatters: <TextInputFormatter>[ FilteringTextInputFormatter.allow( RegExp("[0-9a-zA-Z]"), ), ],
If the user paste a string that contains other signs they will be deleted automaticly but the user might not see that so I want to show a warning to him.
I appriciate all help.
CodePudding user response:
You can use Toast Package or SnackBar
Example of Toast:
Fluttertoast.showToast(
msg: "Title or Content is empty",
toastLength: Toast.LENGTH_SHORT,
gravity: ToastGravity.BOTTOM,
timeInSecForIosWeb: 1,
backgroundColor: Colors.white,
textColor: Colors.black,
fontSize: 16.0);
Example of SnackBar (from my code, on the snackbar there is a button to roll back the deletion and the object will be restored):
ScaffoldMessenger.of(context)
..removeCurrentSnackBar()
..showSnackBar(
SnackBar(
content: Text(
"Deleted \"Item number - ${deletedItem.id}\""),
action: SnackBarAction(
label: "UNDO",
onPressed: () {
setState(() =>
TranslationsDbConnection.createTranslation(
deletedItem));
translations.insert(0, deletedItem);
},
),
),
);
These 2 techniques are used for different purposes, but Toast looks more attractive and unobtrusive.
CodePudding user response:
Thanks for your answeres but I solved it on my own as follows:
The inputFormatter blocks all unallowed signs and won't show them in onChanged value of the textController but the onChanged function is triggered and stays even. So I added the following code to the onChanged: function:
onChanged: (val) {
if (val.length.isEven) {
showSnackBar(
context,
'You entered an unallowed sign!',
icon: Icons.warning_outlined, // this is from my own class showSnackBar which shows a Row with an optional Icon
);
}
Everytime the user types an unallowed sign this warning pops up because the textcontroller changed but the value of it stays the same.
If there are parts I can do better please comment and I'll correct them.
The complete Code of the TextFormField including the inputFormatters:
TextFormField(
inputFormatters: <TextInputFormatter>[
FilteringTextInputFormatter.allow(
RegExp("[0-9a-zA-Z]"),
),
],
obscureText: false,
controller: _controller,
decoration: InputDecoration(
labelText:
'title',
),
onChanged: (val) {
if (val.length.isEven) {
showSnackBar(
context,
'Unallowd sign typed in!',
icon: Icons.warning_outlined,
);
}
model.textChanged(val);
},
),
Thanks