Want to listen focus change in flutter? Here is fully correct answer. addListener shall be in initState(), not build(), because that would result in adding a listener every time a widget is built and you most likely don’t want that.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 | class _SomeWidgetState extends State<SomeWidget> { final FocusNode _focusNode = FocusNode(); @override void initState() { super.initState(); _focusNode.addListener(() { print("Has focus: ${_focusNode.hasFocus}"); }); } @override Widget build(BuildContext context) { return TextField(focusNode: _focusNode); } @override void dispose() { _focusNode.dispose(); super.dispose(); } } |
If you like this question & answer and want to contribute, then write your question & answer and email to freewebmentor[@]gmail.com. Your question and answer will appear on FreeWebMentor.com and help other developers.