insertTextAtPosition method

Future<void> insertTextAtPosition(
  1. String text, {
  2. Position? position,
})

Inserts text at the given position. If the Position is not passed in, use the current selection. If there is no position, or if the selection is not collapsed, do nothing. Then it inserts the text at the given position.

Implementation

Future<void> insertTextAtPosition(
  String text, {
  Position? position,
}) async {
  // If the position is not passed in, use the current selection.
  position ??= selection?.start;

  // If there is no position, or if the selection is not collapsed, do nothing.
  if (position == null || !(selection?.isCollapsed ?? false)) {
    return;
  }

  final path = position.path;
  final node = getNodeAtPath(path);

  if (node == null) {
    return;
  }

  // Get the transaction and the path of the next node.
  final transaction = this.transaction;
  final delta = node.delta;
  if (delta == null) {
    return;
  }

  // Insert the text at the given position.
  transaction.insertText(node, position.offset, text);

  // Set the selection to be at the beginning of the new paragraph.
  transaction.afterSelection = Selection.collapsed(
    Position(
      path: path,
      offset: position.offset + text.length,
    ),
  );

  // Apply the transaction.
  return apply(transaction);
}