How to add clear button to TextField Widget

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

    If you want a ready-to-use Widget, which you can just put in a file and then have a reusable element you can use everywhere by inserting ClearableTextField(), use this piece of code:

    import 'package:flutter/material.dart';
    
    class ClearableTexfield extends StatefulWidget {
      ClearableTexfield({
        Key key,
        this.controller,
        this.hintText = 'Enter text'
      }) : super(key: key);
    
      final TextEditingController controller;
      final String hintText;
    
      @override
      State createState() {
        return _ClearableTextfieldState();
      }
    }
    
    class _ClearableTextfieldState extends State {
      bool _showClearButton = false;
    
      @override
      void initState() {
        super.initState();
        widget.controller.addListener(() {
          setState(() {
            _showClearButton = widget.controller.text.length > 0;
          });
        });
      }
    
      @override
      Widget build(BuildContext context) {
        return TextField(
          controller: widget.controller,
          decoration: InputDecoration(
            hintText: widget.hintText,
            suffixIcon: _getClearButton(),
          ),
        );
      }
    
      Widget _getClearButton() {
        if (!_showClearButton) {
          return null;
        }
    
        return IconButton(
          onPressed: () => widget.controller.clear(),
          icon: Icon(Icons.clear),
        );
      }
    }
    

    Further explanations can be found on this page:

    https://www.flutterclutter.dev/flutter/tutorials/text-field-with-clear-button/2020/104/

    It also builds upon IconButton, but has the advantage of only displaying the clear button when there is text inside the textfield.

    Looks like this:

提交回复
热议问题