如何在颤动中听到焦点的变化?

在 Android 中,我们可以调用 setOnFocusChangeListener(),在 onFocusChanged()方法中做一些事情,但是 flutter 不提供 onFocus()接口,比如 GestureDetector 中的 onTap()或 RawKeyboardListener 中的 onKey()

我读过 flutter api 关于焦点的 https://docs.flutter.io/flutter/widgets/focusmanager-class.html 但我找不到办法实现我的请求,谁能帮帮我?

76949 次浏览

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

Using FocusNode

Here is a 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.

import 'package:flutter/material.dart';


class SomeWidget extends StatefulWidget {
@override
_SomeWidgetState createState() => _SomeWidgetState();
}


class _SomeWidgetState extends State<SomeWidget> {
final _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();
}
}

Using flutter_hooks package

If you're by any chance using the flutter_hooks package, there is a dedicated useFocusNode hook.

import 'package:flutter/material.dart';
import 'package:flutter_hooks/flutter_hooks.dart';


class SomeWidget extends HookWidget {
@override
Widget build(BuildContext context) {
final focusNode = useFocusNode();
useEffect(() {
focusNode.addListener(() {
print("Has focus: ${focusNode.hasFocus}");
});
return; // You need this return if you have missing_return lint
}, [focusNode]);


return TextField(focusNode: focusNode);
}
}

In addtion you can use Focus widget.

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