How to add clear button to TextField Widget

后端 未结 12 1425
南笙
南笙 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条回答
  •  -上瘾入骨i
    2020-12-22 23:13

    Here’s another answer expanding a bit on @Vilokan Lab’s answer, which wasn’t really doing it for me since FlatButton has a minimum width of 88.0, and thus the clear button was not appearing right-aligned with the TextField at all.

    So I went ahead and made my own button class, and applied that using a Stack, here is my process:

    Button class:

    class CircleIconButton extends StatelessWidget {
    final double size;
    final Function onPressed;
    final IconData icon;
    
    CircleIconButton({this.size = 30.0, this.icon = Icons.clear, this.onPressed});
    
    @override
    Widget build(BuildContext context) {
      return InkWell(
        onTap: this.onPressed,
        child: SizedBox(
            width: size,
            height: size,
            child: Stack(
              alignment: Alignment(0.0, 0.0), // all centered
              children: [
                Container(
                  width: size,
                  height: size,
                  decoration: BoxDecoration(
                      shape: BoxShape.circle, color: Colors.grey[300]),
                ),
                Icon(
                  icon,
                  size: size * 0.6, // 60% width for icon
                )
              ],
            )));
      }
    }
    

    Then apply like so as InputDecoration to your TextField:

    var myTextField = TextField(
      controller: _textController,
      decoration: InputDecoration(
          hintText: "Caption",
          suffixIcon: CircleIconButton(
            onPressed: () {
              this.setState(() {
                _textController.clear();
              });
            },
          )),
      },
    );
    

    To get this:

    Unhighlighted state

    Highlighted / selected state.

    Note this colouring comes free when you use suffixIcon.


    Note you can also Stack it in your TextField like this, but you won't get the auto-colouring you get when you use suffixIcon:

    var myTextFieldView = Stack(
      alignment: Alignment(1.0,0.0), // right & center
      children: [
        TextField(
          controller: _textController,
          decoration: InputDecoration(hintText: "Caption"),
        ),
        Positioned(
          child: CircleIconButton(
            onPressed: () {
              this.setState(() {
                _textController.clear();
              });
            },
          ),
        ),
      ],
    );
    

提交回复
热议问题