How to add clear button to TextField Widget

后端 未结 12 1469
南笙
南笙 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:51

    Here's a snippet of my code that works.

    What it does: only show clear button if text field value is not empty

    class _MyTextFieldState extends State {
      TextEditingController _textController;
      bool _wasEmpty;
    
      @override
      void initState() {
        super.initState();
        _textController = TextEditingController(text: widget.initialValue);
        _wasEmpty = _textController.text.isEmpty;
        _textController.addListener(() {
          if (_wasEmpty != _textController.text.isEmpty) {
            setState(() => {_wasEmpty = _textController.text.isEmpty});
          }
        });
      }
    
      @override
      void dispose() {
        _textController.dispose();
        super.dispose();
      }
    
      @override
      Widget build(BuildContext context) {
        return TextFormField(
              controller: _textController,
              decoration: InputDecoration(
                labelText: widget.label,
                suffixIcon: _textController.text.isNotEmpty
                    ? Padding(
                        padding: const EdgeInsetsDirectional.only(start: 12.0),
                        child: IconButton(
                          iconSize: 16.0,
                          icon: Icon(Icons.cancel, color: Colors.grey,),
                          onPressed: () {
                            setState(() {
                              _textController.clear();
                            });
                          },
                        ),
                      )
                    : null,
              ),);
    ...
    

提交回复
热议问题