insertText method

void insertText(
  1. Node node,
  2. int index,
  3. String text, {
  4. Attributes? attributes,
  5. Attributes? toggledAttributes,
})

Inserts the text at the given index.

If the attributes is null, the attributes of the previous character will be used. If the attributes is not null, the attributes will be used.

Implementation

void insertText(
  Node node,
  int index,
  String text, {
  Attributes? attributes,
  Attributes? toggledAttributes,
}) {
  final delta = node.delta;
  if (delta == null) {
    assert(false, 'The node must have a delta.');
    return;
  }

  if (index < 0 || index > delta.length) {
    Log.editor.info('The index($index) is out of range or negative.');
    return;
  }

  final newAttributes = attributes ?? delta.sliceAttributes(index) ?? {};

  if (toggledAttributes != null) {
    newAttributes.addAll(toggledAttributes);
  }

  final insert = Delta()
    ..retain(index)
    ..insert(text, attributes: newAttributes);

  addDeltaToComposeMap(node, insert);

  afterSelection = Selection.collapsed(
    Position(path: node.path, offset: index + text.length),
  );
}