'FocusAttachment Is Not Working When Navigating Away and Back From Flutter Web
I have a Flutter app for web that checks if control is pressed, and is managed in my internal state. Using this answer I created the code to check if control is pressed. My code is below:
class _CanvasViewState extends ConsumerState<CanvasView> {
late final FocusNode focus;
late final FocusAttachment _nodeAttachment;
@override
void initState() {
focus = FocusNode();
_nodeAttachment = focus.attach(context, onKey: (node, event) {
// preform call to provider
return KeyEventResult.ignored;
});
focus.requestFocus();
super.initState();
}
@override
void dispose() {
focus.dispose();
super.dispose();
}
_CanvasViewState();
@override
Widget build(BuildContext context) {
_nodeAttachment.reparent();
....
}
}
This works fine initially. However, if I go to a different application and come back it no longer works. The function callback inside of my initState
is no longer called when I press control. Am I going about checking if control is pressed completely wrong or how can this be accomplished?
Solution 1:[1]
Instead of initState()
try using didChangeDependencies()
like this:
bool _init = true;
@override
void didChangeDependencies() {
if(_init == true){
focus = FocusNode();
_nodeAttachment = focus.attach(context, onKey: (node, event) {
// preform call to provider
return KeyEventResult.ignored;
});
focus.requestFocus();
_init = false;
}
super.didChangeDependencies();
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | MendelG |