Today, when I was writing code practice, I suddenly wanted to delete TextFiled above problems. The results were not deleted, and there were few searches. Here I write a note for your reference

  • Have a problem

Have a problem

TextEditingController will not respond and will keep refreshing TextFiled so that the text is never assigned.

TextEditingController _textcontroller; TextField( controller: _textcontroller = TextEditingController(), decoration: InputDecoration( hintText: SuffixIcon: IconButton(icon: icon (icon.delete), onPressed: (){setState(() {_textController?.clear(); }); }, ) ), onChanged: (value) { }, ),Copy the code

Effect:



It looked very strange, then through my 10 minutes of thinking and Baidu to find the wrong problem

The problem is with TextEditingController(), because I’m actually refreshing TextField internally every time I type, and then I’m recreating TextEditingController() every time I refresh, so I’m just going to make TextEditingCon Troller () creates it once

Take a look at the changed code:

final TextEditingController _textcontroller = TextEditingController(); TextField(Controller: _textController, decoration: InputDecoration(hintText: "please input a value ", suffixIcon: IconButton(icon: Icon(Icons.delete), onPressed: (){ setState(() { _textcontroller.clear(); }); }, ) ), onChanged: (value) { }, ),Copy the code

Textcontroller.clear (); textController.clear (); methods

Take a look at the results:



If you are not familiar with TextField, please clickFlutter StatefluWidget and Base Components (1.2)In this article I have an introduction to TextField