lilbiscuit
lilbiscuit

Reputation: 2249

Flutter TextFormField with dynamic suffixIcon

The objective is to show/hide a suffixIcon that clears out the field on a Flutter TextFormField. It should only be visible if there is text in the box.

The field looks like this:

TextFormField(                  
  controller: _usernameController,
  decoration: InputDecoration(
    labelText: 'Username',
    suffixIcon: usernameNotEmpty == true ? IconButton(
      onPressed: () {
        _usernameController.clear();
      },
      icon: Icon(Icons.cancel, color: Colors.grey)
    ) : null
  ),                  
)

and the event listener looks like this:

var usernameNotEmpty;
_usernameController.addListener(() {
   usernameNotEmpty = _usernameController.text.length > 0 ? true : false; 
   print(_usernameController.text);
});

So the realtime updated text does appear in the console. But the suffixIcon is never shown. Since the TextFormField doesn't have an onChange event, how can this suffixIcon be shown/hidden?

Upvotes: 6

Views: 9191

Answers (2)

Leo
Leo

Reputation: 505

Use suffix, not suffixIcon. Suffix widget behaves as you expected. it will be shown if TextField is not empty.

TextFormField(                  
  controller: _usernameController,
  decoration: InputDecoration(
    labelText: 'Username',
    suffix: IconButton(
      onPressed: () {
        _usernameController.clear();
      },
      icon: Icon(Icons.cancel, color: Colors.grey)
    )
  ),

Upvotes: 3

lilbiscuit
lilbiscuit

Reputation: 2249

Cleaned up and working:

_usernameController.addListener(() {
  setState(() {}); 
});

TextFormField(                  
  controller: _usernameController,
  decoration: InputDecoration(
    labelText: 'Username',
    suffixIcon: _usernameController.text.length > 0 ? IconButton(
      onPressed: () {
        _usernameController.clear();
      },
      icon: Icon(Icons.cancel, color: Colors.grey)
    ) : null
  ),
)

Upvotes: 10

Related Questions