如何将清除按钮添加到TextField小部件

问题描述:

是否有正确的方法向 TextField 添加清除按钮?

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

就像材料设计指南中的这张图片一样:

Just like this picture from Material design guidelines:

我发现是在 InputDecoration $ c中设置一个清晰的 IconButton $ c>的 suffixIcon

What I found is to set a clear IconButton in the InputDecoration's suffixIcon. Is this the right way?

输出:

创建变量

var _controller = TextEditingController();

和您的 TextField

TextField(
  controller: _controller,
  decoration: InputDecoration(
    hintText: "Enter a message",
    suffixIcon: IconButton(
      onPressed: () => _controller.clear(),
      icon: Icon(Icons.clear),
    ),
  ),
)