insert method

EasyTextChange insert(
  1. int index,
  2. String data, [
  3. EasyAttributeStyles? style,
  4. bool ignoreMerge = false,
])

Inserts text at the specified index with optional styling.

Example:

final text = EasyText.fromStr(text: 'Hello World');
text.insert(6, 'Beautiful '); // Result: 'Hello Beautiful World'
text.insert(6, 'Amazing ', style: EasyAttributeStyles.fromJson({'bold': BoldAttribute()}));

Implementation

EasyTextChange insert(
  int index,
  String data, [
  EasyAttributeStyles? style,
  bool ignoreMerge = false,
]) {
  assert(
    index >= 0 && index <= length,
    'Index must be '
    'between 0 and $length',
  );

  final Characters chars = data.characters;
  final int insertLength = chars.length;
  if (!_dirty) {
    list?.textLength += insertLength;
  }

  style ??= EasyAttributeStyles.empty();
  // if both share the same attributes, just
  // insert the data at the position
  // without splitting
  //
  // this should avoid unlinking instances
  // when not required
  if (this.styles == style && index <= length) {
    if (_length != null) _length = length + insertLength;
    _text = before(math.min(index, length)) +
        chars +
        after(math.min(index, length));
  } else {
    final EasyText part = EasyText.fromStr(text: data).._dirty = true;
    if (index < length) {
      final split = splitAt(index, true);
      // avoid counting the split and the insertAfter setting
      // asDirty to true
      split!
        ..insertBefore(part)
        .._dirty = false;
    } else {
      insertAfter(part);
    }
    part
      .._dirty = false
      ..format(
        style,
        true,
        ignoreMerge,
      );
  }
  return EasyTextChange(
    delta: Delta()
      ..retain(index)
      ..insert(data, style.toJson()),
    inverted: Delta()
      ..retain(index)
      ..delete(insertLength),
    start: index,
    length: insertLength,
  );
}