findFirstFocusInDirection method

  1. @override
FocusNode? findFirstFocusInDirection(
  1. FocusNode currentNode,
  2. TraversalDirection direction
)
override

Returns the first node in the given direction that should receive focus if there is no current focus in the scope to which the currentNode belongs.

This is typically used by inDirection to determine which node to focus if it is called when no node is currently focused.

Implementation

@override
FocusNode? findFirstFocusInDirection(FocusNode currentNode, TraversalDirection direction) {
  final Iterable<FocusNode> nodes = currentNode.nearestScope!.traversalDescendants;
  final List<FocusNode> sorted = nodes.toList();
  final (bool vertical, bool first) = switch (direction) {
    TraversalDirection.up    => (true, false),  // Start with the bottom-most node.
    TraversalDirection.down  => (true, true),   // Start with the topmost node.
    TraversalDirection.left  => (false, false), // Start with the rightmost node.
    TraversalDirection.right => (false, true),  // Start with the leftmost node.
  };
  mergeSort<FocusNode>(sorted, compare: (FocusNode a, FocusNode b) {
    if (vertical) {
      if (first) {
        return a.rect.top.compareTo(b.rect.top);
      } else {
        return b.rect.bottom.compareTo(a.rect.bottom);
      }
    } else {
      if (first) {
        return a.rect.left.compareTo(b.rect.left);
      } else {
        return b.rect.right.compareTo(a.rect.right);
      }
    }
  });

  return sorted.firstOrNull;
}