How to add clear button to TextField Widget

后端 未结 12 1451
南笙
南笙 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 23:09

    Search TextField with icon and clear button

    import 'package:flutter/material.dart';
    
      class SearchTextField extends StatefulWidget{
        @override
        State createState() {
          // TODO: implement createState
          return new SearchTextFieldState();
        }
      }
    
      class SearchTextFieldState extends State{
        final TextEditingController _textController = new TextEditingController();
    
        @override
        Widget build(BuildContext context) {
          // TODO: implement build
          return new Row(children: [
            new Icon(Icons.search, color: _textController.text.length>0?Colors.lightBlueAccent:Colors.grey,),
            new SizedBox(width: 10.0,),
            new Expanded(child: new Stack(
                alignment: const Alignment(1.0, 1.0),
                children: [
                  new TextField(
                    decoration: InputDecoration(hintText: 'Search'),
                    onChanged: (text){
                      setState(() {
                        print(text);
                      });
                    },
                    controller: _textController,),
                  _textController.text.length>0?new IconButton(icon: new Icon(Icons.clear), onPressed: () {
                    setState(() {
                      _textController.clear();
                    });
                  }):new Container(height: 0.0,)
                ]
            ),),
          ],);
        }
      }
    

提交回复
热议问题