How to change TextField value without having to delete it first (Flutter)
1,181
Solution 1
One way you can do this is like this.
class MyWidget extends StatefulWidget {
@override
_MyWidgetState createState() => _MyWidgetState();
}
class _MyWidgetState extends State<MyWidget> {
TextEditingController tc = TextEditingController();
@override
Widget build(BuildContext context) {
return TextField(
controller: tc,
onChanged: (newText){
if(newText.length == 2){
tc.text = newText.substring(1);
tc.selection = TextSelection.fromPosition(TextPosition(offset: 1));
}
}
);
}
}
Solution 2
You can wrap the text field in a gestureDetector then use the onTap property to set the textEditingController.text value to an empty string
Author by
Admin
Updated on December 24, 2022Comments
-
Admin over 1 year
I am trying to make a Phone Verification input field with six digits, all having max length of 1 digit. My issue is that I want the user to be able to change the value they entered without having to delete the old value. For example, the user typed "2" to a box, and when they clicked the box and typed "3", the value should change automatically.
-
Guillaume Roux over 3 yearsPlease provide the code you use so we can help.
-
-
Admin over 3 yearsThis worked just fine, thank you very much for helping out a newbie :)