Search code examples
flutterfocus

Flutter focus: is FocusNode the thing that has focus?


In the focus system, there are a lot of widgets such as Focus, FocusNode, FocusScope, FocusScopeNode, etc. I'm trying to understand the focus system and have two specific questions:

  1. Is a FocusNode the thing that is considered to be in focus? I know that FocusScopeNode has a hasFocus but it's not as if you can focus on a FocusScopeNode because you'd actually be focusing on it's FocusNode?

  2. Is calling .requestFocus() or .unfocus() of a FocusNode the only way that focus will be removed or given to a FocusNode? (except for autofocus) In other words, things won't automatically be focused by clicking, tapping, or hitting TAB on them?


Solution

  • In the Flutter framework's focus system, a FocusNode is a representation of the focus state for a particular widget or group of widgets. When a FocusNode has focus, it means that it is currently the widget that is responding to keyboard events and other forms of input focus.

    A FocusScopeNode is a widget that is used to create a scope within the focus tree. A scope defines a new node in the focus tree, and all FocusNodes within that scope are descendants of that scope's node. A FocusScopeNode also has a hasFocus property, which indicates whether any of the FocusNodes within its scope currently has focus.

    1. To answer your first question, a FocusNode is considered to be in focus when its hasFocus property is set to true. A FocusScopeNode is not something that can be focused on directly, but rather it is a way of organizing the focus tree and determining which nodes are within a particular scope.

    2. To answer your second question, calling requestFocus() or unfocus() on a FocusNode is not the only way to remove or give focus to a FocusNode. In Flutter, focus can also be changed by clicking or tapping on a widget, or by using the TAB key to navigate through the focus tree. However, these methods of changing focus will only work if the FocusNode is part of the focus tree and is attached to a widget that is part of the widget hierarchy.