onKeyPressed property

  1. @experimental
KeyEventResult? Function(KeyEvent event, Node? node)? onKeyPressed
final

A handler for keys that are pressed when the editor is focused.

This feature is supported on desktop devices and mobile devices with a hardware keyboard connected. It is not supported by virtual on-screen keyboards of touch devices.

Example:

To prevent the user from removing any Embed Object, try:

onKeyPressed: (event, node) {
  if (event.logicalKey == LogicalKeyboardKey.backspace &&
      (node is Line || node is Block)) {
    // Use [DeltaIterator] to jump directly to the position before the current.
    final iterator = DeltaIterator(_controller.document.toDelta())
          ..skip(_controller.selection.baseOffset - 1);
    // Get the [Operation] where the caret is on
    final cur = iterator.next();
    final isOperationWithEmbed = cur.data is! String && cur.data != null;
    if (isOperationWithEmbed) {
        // Ignore this [KeyEvent] to prevent the user from removing the [Embed Object].
        return KeyEventResult.handled;
    }
  }
  // Apply custom logic or return null to use default events
  return null;
},

Implementation

@experimental
final KeyEventResult? Function(KeyEvent event, Node? node)? onKeyPressed;