2

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?

Gabe
  • 5,643
  • 3
  • 26
  • 54

1 Answers1

-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();
}
MendelG
  • 14,885
  • 4
  • 25
  • 52
Ali Solanki
  • 640
  • 7
  • 16
  • What is the difference between this and `initState` if you are only running it when `_init` is true? – Gabe Apr 15 '22 at 13:34
  • @Gabe This is how build occurs: initState -> build widgets -> didChangeDependencies You can use context in didChangeDependencies but not in initState – Ali Solanki Apr 21 '22 at 05:23
  • Thanks for the clarification. Unfortunately, this code still does not work. – Gabe Apr 22 '22 at 12:56