Created
June 12, 2020 07:19
-
-
Save Schnodderbalken/8349df04ded812f48724a4f78da59ba0 to your computer and use it in GitHub Desktop.
Flutter text field with clear button example
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class MyHomePage extends StatefulWidget { | |
MyHomePage({Key key, this.title}) : super(key: key); | |
final String title; | |
@override | |
_MyHomePageState createState() => _MyHomePageState(); | |
} | |
class _MyHomePageState extends State<MyHomePage> { | |
final TextEditingController _textEditingController = TextEditingController(); | |
bool _showClearButton = false; | |
@override | |
void initState() { | |
super.initState(); | |
_textEditingController.addListener(() { | |
setState(() { | |
_showClearButton = _textEditingController.text.length > 0; | |
}); | |
}); | |
} | |
@override | |
Widget build(BuildContext context) { | |
return Scaffold( | |
appBar: AppBar( | |
title: Text(widget.title), | |
), | |
body: Align( | |
alignment: Alignment.bottomCenter, | |
child: Container( | |
padding: EdgeInsets.all(16), | |
child: _getTextField() | |
) | |
), | |
); | |
} | |
TextField _getTextField() { | |
return TextField( | |
controller: _textEditingController, | |
decoration: InputDecoration( | |
hintText: "Enter a beautiful text", | |
suffixIcon: _getClearButton(), | |
), | |
); | |
} | |
Widget _getClearButton() { | |
if (!_showClearButton) { | |
return null; | |
} | |
return IconButton( | |
onPressed: () => _textEditingController.clear(), | |
icon: Icon(Icons.clear), | |
); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment