Reputation: 1629
I've already read this. how to make clear button appears when text is enter in TextFormField in flutter but It doesn't work, and also I found that the textfield doesn't recognize the change when text is typed. If you know the solution, I really appreciate it if you let me know.
Here's my code below :
TextField(
controller: _controller,
onChanged: (String word) {
this.word = word;
_controller.text = word;
},
style: TextStyle(
fontSize: 30,
fontWeight: FontWeight.w800,
color: Colors.black),
decoration: InputDecoration(
isDense: true,
suffix: _controller.text.length > 0
? Padding(
padding: const EdgeInsetsDirectional.only(
bottom: 2),
child: IconButton(
onPressed: () => _controller.clear(),
icon: Icon(Icons.clear),
iconSize: 25,
color: Colors.black.withOpacity(0.5),
))
: null,
contentPadding:
EdgeInsets.only(left: 8.5, bottom: 3),
enabledBorder: UnderlineInputBorder(
borderSide: BorderSide(color: Colors.black)),
focusedBorder: UnderlineInputBorder(
borderSide: BorderSide(color: Colors.black),
),
hintText: "Add text",
hintStyle: TextStyle(
fontSize: 29.0,
color: Colors.black.withOpacity(0.5)),
)),
What I want to make :
Upvotes: 0
Views: 3119
Reputation: 1452
First of all, in the onChanged(), you're just assigning the value to controller.text without telling the widget to rebuild according to the changes. Therefore, you must have a setState() inside onChanged().
Second, don't reassign controller.text, since that will cause the error of the cursor always jump to the start (don't ask me why, I just know the error is there). So instead, make a new variable type String and assign value to it in onChanged(). Then when checking the condition to show or hide the suffix icon, check the condition with that new String, not with controller.text.
Upvotes: 1
Reputation: 2073
Try using.
suffix = _controller.text !=null?Padding(
padding: const EdgeInsetsDirectional.only(
bottom: 2),
child: IconButton(
onPressed: () => _controller.clear(),
icon: Icon(Icons.clear),
iconSize: 25,
color: Colors.black.withOpacity(0.5),
))
: null,
Upvotes: -1