replaceText method

void replaceText(
  1. int index,
  2. int len,
  3. Object? data,
  4. TextSelection? textSelection,
  5. {bool ignoreFocus = false,
  6. bool shouldNotifyListeners = true}
)

Implementation

void replaceText(
  int index,
  int len,
  Object? data,
  TextSelection? textSelection, {
  bool ignoreFocus = false,
  bool shouldNotifyListeners = true,
}) {
  assert(data is String || data is Embeddable || data is Delta);

  if (onReplaceText != null && !onReplaceText!(index, len, data)) {
    return;
  }

  Delta? delta;
  if (len > 0 || data is! String || data.isNotEmpty) {
    delta = document.replace(index, len, data);
    var shouldRetainDelta = toggledStyle.isNotEmpty &&
        delta.isNotEmpty &&
        delta.length <= 2 &&
        delta.last.isInsert &&
        // pasted text should not use toggledStyle
        (data is! String || data.length < 2);
    if (shouldRetainDelta &&
        toggledStyle.isNotEmpty &&
        delta.length == 2 &&
        delta.last.data == '\n') {
      // if all attributes are inline, shouldRetainDelta should be false
      final anyAttributeNotInline =
          toggledStyle.values.any((attr) => !attr.isInline);
      if (!anyAttributeNotInline) {
        shouldRetainDelta = false;
      }
    }
    if (shouldRetainDelta) {
      final retainDelta = Delta()
        ..retain(index)
        ..retain(data is String ? data.length : 1, toggledStyle.toJson());
      document.compose(retainDelta, ChangeSource.local);
    }
  }

  if (textSelection != null) {
    if (delta == null || delta.isEmpty) {
      _updateSelection(textSelection, ChangeSource.local);
    } else {
      final user = Delta()
        ..retain(index)
        ..insert(data)
        ..delete(len);
      final positionDelta = getPositionDelta(user, delta);
      _updateSelection(
        textSelection.copyWith(
          baseOffset: textSelection.baseOffset + positionDelta,
          extentOffset: textSelection.extentOffset + positionDelta,
        ),
        ChangeSource.local,
      );
    }
  }

  if (ignoreFocus) {
    ignoreFocusOnTextChange = true;
  }
  if (shouldNotifyListeners) {
    notifyListeners();
  }
  ignoreFocusOnTextChange = false;
}