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,
]) {
  final int insertLength = data.characters.length;
  assert(
    index >= 0 && index <= length,
    'Index must be '
    'between 0 and $length',
  );
  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) {
    final Characters chars = data.characters;
    if (_length != null) _length = length + chars.length;
    _text = before(math.min(index, length)) +
        chars +
        after(math.min(index, length));
  } else {
    final EasyText part = EasyText.fromStr(text: data);
    if (index < length) {
      splitAt(index)!.insertBefore(part);
    } else {
      insertAfter(part);
    }
    part.format(
      style,
      true,
      ignoreMerge,
    );
  }
  return EasyTextChange(
    delta: Delta()
      ..retain(index)
      ..insert(data, style.toJson()),
    inverted: Delta()
      ..retain(index)
      ..delete(insertLength),
    start: index,
    length: insertLength,
  );
}