Reputation: 131
I have a TextFormField that, if the user leaves it, should fill with specific Text. So for example, if the user edits the field and enters "Test", and I don't want to allow the String "Test", then as soon as the field looses focus it should replace the Text with "Sike!". So something like onChanged, but the event being the loss of Focus, not a change of value, which is what I had so far:
TextFormField(
controller: myController,
onChanged: (value) {
if (value == "Test"){
myController.text = "Sike!";
}
},
.............
.............
Upvotes: 0
Views: 1397
Reputation: 5423
One way you can do this is like so.
class _DemoState extends State<Demo> {
final node = FocusNode();
final tc = TextEditingController();
@override
void initState() {
node.addListener(() {
if (!node.hasFocus && tc.text == 'Test') {
tc.text = "Sike!";
}
});
super.initState();
}
@override
Widget build(BuildContext context) {
return TextFormField(
controller: tc,
focusNode: node,
);
}
}
Upvotes: 3