Focus in Flutter: Tree, Accessibility and Keyboard

Focus in Flutter: Tree, Accessibility and Keyboard

Focus is a key system in Flutter that manages which element is active and directs keyboard input accordingly. It also enables easy navigation between elements, ensuring smooth tab traversal for better accessibility. In this article we will understand how all these works together.

Outline

  1. Focus Tree
  2. Keyboard and Shortcuts
  3. Focus Traversal

Focus Tree

Focus nodes form a tree that sparsely mirrors the widget tree, representing all elements that can receive focus.

Additionally, there is the FocusScopeNode, that manages a stack of focused children, where the topmost element (i.e. last item in the array) is currently focused one. FocusScopeNode is automatically created in the root of the tree and called rootScope.

Other nodes are added to the tree via Focus and FocusScope widgets accordingly. During instantiation, they attach their BuildContext to the node, so that the node can find the correct ancestor to be reparented to (see reparent). When the widget is disposed, it calls detach method that removes the node from the tree.

Focus Manager

Focus manager is responsible for managing the focus tree, with the following responsibilities:

  • Keeping track of the current primary focus
  • Holding the root scope of the focus tree
  • Distributing keyboard events among nodes

Read more