Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Flutter TextField with IconButton

Tags:

flutter

I have two problems with this widget. When adding the suffix: IconButton... it adds what looks like a padding inside the textfield. And how can I show the suffix icon when _searchController.text is not empty. I tried _searchController.text != null ? IconButton(...): 'not sure what to return here'

  Widget _searchBox() {
    return TextField(
      controller: _searchController,
      decoration: InputDecoration(
        labelText: "Search",
        hintText: "Search",
        prefixIcon: Icon(Icons.search),
        suffix: IconButton(
          icon: Icon(Icons.clear),
          onPressed: () => _searchController.clear(),
        ),
        border: OutlineInputBorder(
          borderRadius: BorderRadius.all(
            Radius.circular(10.0),
          ),
        ),
      ),
    );
  }

With suffix:

enter image description here

Withoug suffix:

enter image description here

like image 531
Ciprian Avatar asked Mar 18 '26 14:03

Ciprian


1 Answers

I ended up using ideas from both answers. One didn't explain how to show and hide the icon while the other seemed a bit too complicated. All I did is _searchController.text.isEmpty

  Widget _searchBox() {
    return TextField(
      controller: _searchController,
      decoration: InputDecoration(
        labelText: "Search",
        hintText: "Search",
        prefixIcon: Icon(Icons.search),
        suffixIcon: _searchController.text.isEmpty
            ? null
            : InkWell(
                onTap: () => _searchController.clear(),
                child: Icon(Icons.clear),
              ),
        border: OutlineInputBorder(
          borderRadius: BorderRadius.all(
            Radius.circular(10.0),
          ),
        ),
      ),
    );
  }
like image 51
Ciprian Avatar answered Mar 21 '26 10:03

Ciprian