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

Share:
1,181
Admin
Author by

Admin

Updated on December 24, 2022

Comments

  • Admin
    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
      Guillaume Roux over 3 years
      Please provide the code you use so we can help.
  • Admin
    Admin over 3 years
    This worked just fine, thank you very much for helping out a newbie :)