Element focus change on Flutter
Whenever an element receives focus, it should not automatically trigger an event which changes context
. Example of changing context include, but are not limited to: automatically submitting data, opening a new screen or moving to another element. Focus should only be moved deliberately by the user.
In Flutter, you can use FocusNode
to listen to focus changes. The flutter_hooks
package includes a method named useFocusNode
which makes it easier to listen to to focus changes.
Be careful when using the FocusNode
listener: do not trigger any context change because they might confuse users.
import 'package:flutter/material.dart';
import 'package:flutter_hooks/flutter_hooks.dart';
class FocusWidget extends HookWidget {
@override
Widget build(BuildContext context) {
final focusNode = useFocusNode();
useEffect(() {
focusNode.addListener(() {
// Do not change context
});
return;
}, [focusNode]);
return TextField(focusNode: focusNode);
}
}