Solved: How to listen focus change in flutter?

Question

Asked by coder.john on December 25, 2017 (source).

In Android, we can call setOnFocusChangeListener(), do something in onFocusChanged() method, but flutter does not provider onFocus() interface like onTap() in GestureDetector or onKey() in RawKeyboardListener.

I have read flutter api about focus, https://docs.flutter.io/flutter/widgets/FocusManager-class.html but I can't find a way to realize my request, anyone who can give me a hand?

Answer

Question answered by Hemanth R (source).

I suppose you are looking for FocusNode class. Use addListener method to add a listener function that listens to focus change.

Example
declare and define FocusNode

 var focusNode = FocusNode();
  @override
  void initState() {
    focusNode.addListener(() {
      print(focusNode.hasFocus);
    });
    super.initState();
  }

Use focus node in textfield

TextField(
            focusNode: focusNode,
          ),

Output

when textfield is focus you will get true else false

DART FLUTTER FOCUS
SHARE: