onKey method

  1. @override
bool onKey(
  1. KeyEvent event,
  2. RenderContext ctx
)
override

Implementation

@override
bool onKey(KeyEvent event, RenderContext ctx) {
  if (!state.open) {
    if (event.key == NamedKey.enter || event.char == ' ') {
      state.open = true;
      state.highlightedIndex = selected == null
          ? 0
          : options
              .indexWhere((o) => o == selected)
              .clamp(0, options.length - 1);
      return true;
    }
    return false;
  }
  if (event.key == NamedKey.escape) {
    state.open = false;
    return true;
  }
  if (event.key == NamedKey.arrowDown || event.char == 'j') {
    state.highlightedIndex =
        (state.highlightedIndex + 1).clamp(0, options.length - 1);
    return true;
  }
  if (event.key == NamedKey.arrowUp || event.char == 'k') {
    state.highlightedIndex =
        (state.highlightedIndex - 1).clamp(0, options.length - 1);
    return true;
  }
  if (event.key == NamedKey.enter) {
    if (options.isNotEmpty) {
      onChanged?.call(options[state.highlightedIndex]);
    }
    state.open = false;
    return true;
  }
  return false;
}