How to add clear button to TextField Widget

后端 未结 12 1429
南笙
南笙 2020-12-22 22:11

Is there a proper way to add a clear button to the TextField?

Just like this picture from Material design guidelines:

What I found is

12条回答
  •  一生所求
    2020-12-22 22:55

    Didn't want to go the StatefulWidget route. Here's an example using TextEditingController and StatelessWidget (with Providers pushing updates). I keep the controller in the static field.

    class _SearchBar extends StatelessWidget {
      static var _controller = TextEditingController();
    
      @override
      Widget build(BuildContext context) {
        var dictionary = Provider.of(context);
    
        return TextField(
            controller: _controller,
            autofocus: true,
            onChanged: (text) {
              dictionary.lookupWord = text;
            },
            style: TextStyle(fontSize: 20.0),
            decoration: InputDecoration(
                border: InputBorder.none,
                hintText: 'Search',
                suffix: GestureDetector(
                  onTap: () {
                    dictionary.lookupWord = '';
                    _controller.clear();
                  },
                  child: Text('x'),
                )));
      }
    }
    

提交回复
热议问题