Martin Schultz
Martin Schultz

Reputation: 2861

Flutter TextField clear button position wrong

I want to have a clear button for my textfield. I found an example of how to add it using decoration, but its position is completely off. How can I adjust the position of the icon?

Also, I cannot get the input text to be centered in the input field. I didn't find anything how to vertically center the text in the input box.

Thanks!

...
TextEditingController _textFieldController = TextEditingController();
...

Widget searchField(BuildContext context) {
  return Container(
    width: 200,
    height: 30,
    color: Colors.grey[250],
    child: TextField(
      controller: _textFieldController,
      decoration: InputDecoration(
        suffix: IconButton(
          padding: EdgeInsets.all(0),
          alignment: Alignment.bottomLeft,
          icon: Icon(Icons.cancel),
          onPressed: _onClear,
        ),
        border: OutlineInputBorder(),
        hintText: 'Blablabla',
      ),
    )
  );
}

enter image description here

Upvotes: 3

Views: 6948

Answers (2)

rinde
rinde

Reputation: 1263

There are three changes needed to reach the desired result:

  1. Use suffixIcon instead of suffix
  2. Remove vertical content padding, e.g. contentPadding: EdgeInsets.only(left:5) to vertically align the text when it is vertically constrained (e.g. the container height of 30).
  3. Remove padding in the IconButton: padding: EdgeInsets.zero to align the icon.

The complete code is:

return Container(
  width: 200,
  height: 30,
  color: Colors.grey[250],
  child: TextField(
    controller: _textFieldController,
    decoration: InputDecoration(
      contentPadding: EdgeInsets.only(left: 5),
      suffixIcon: IconButton(
        padding: EdgeInsets.zero,
        icon: Icon(Icons.cancel),
        onPressed: () => print("clear"),
      ),
      border: OutlineInputBorder(),
      hintText: 'Blablabla',
    ),
  )
);

Final result:

screenshot of search field with correct formatting

Upvotes: 4

diegoveloper
diegoveloper

Reputation: 103431

Reduce the padding of the InputDecoration to zero.

             TextField(
               decoration: InputDecoration(
                              contentPadding: EdgeInsets.zero,

Upvotes: 1

Related Questions