How to listen focus change in flutter?

2020-05-30 02:43发布

问题:

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?

回答1:

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



回答2:

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.

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();
  }
}


回答3:

In addtion you can use Focus widget.

Focus(
  child: TextFormField(...),
  onFocusChange: (hasFocus) {
    if(hasFocus) {
      // do staff
    }
  },
)