handleKeyEvent method

KeyEventResult handleKeyEvent(
  1. KeyEvent event, {
  2. required ValueChanged<String>? onSubmit,
  3. bool allowSubmit = true,
})

Applies the composer's Enter rules to event.

Call it from a Focus.onKeyEvent above the text field. Enter sends the draft through onSubmit when submit gives one; either way the key is handled, so it never falls through to a newline. A repeat of a held Enter is handled without sending. allowSubmit false keeps Enter handled but sends nothing, for a host that disables sending.

The key is left to the field (ignored) when onSubmit is null, which makes the composer a plain multiline field, when Shift is held, and while an input method is composing.

Implementation

KeyEventResult handleKeyEvent(
  KeyEvent event, {
  required ValueChanged<String>? onSubmit,
  bool allowSubmit = true,
}) {
  if (event is KeyUpEvent) return KeyEventResult.ignored;
  final isEnter =
      event.logicalKey == LogicalKeyboardKey.enter ||
      event.logicalKey == LogicalKeyboardKey.numpadEnter;
  if (!isEnter ||
      onSubmit == null ||
      HardwareKeyboard.instance.isShiftPressed ||
      isComposing) {
    return KeyEventResult.ignored;
  }
  if (event is KeyDownEvent && allowSubmit) {
    final prompt = submit();
    if (prompt != null) onSubmit(prompt);
  }

  return KeyEventResult.handled;
}