correctCaretOffset function Null safety

TextEditingValue correctCaretOffset(
  1. TextEditingValue value,
  2. InlineSpan textSpan,
  3. TextInputConnection? textInputConnection,
  4. {TextSelection? newSelection}
)

correct caret Offset make sure caret is not in text when caretIn is false

Implementation

TextEditingValue correctCaretOffset(TextEditingValue value, InlineSpan textSpan,
    TextInputConnection? textInputConnection,
    {TextSelection? newSelection}) {
  final TextSelection selection = newSelection ?? value.selection;

  if (selection.isValid && selection.isCollapsed) {
    int caretOffset = selection.extentOffset;

    // correct caret Offset
    // make sure caret is not in text when deleteAll is true
    //
    textSpan.visitChildren((InlineSpan span) {
      if (span is SpecialInlineSpanBase &&
          (span as SpecialInlineSpanBase).deleteAll) {
        final SpecialInlineSpanBase specialTs = span as SpecialInlineSpanBase;
        if (caretOffset >= specialTs.start && caretOffset <= specialTs.end) {
          if (caretOffset >
              (specialTs.end - specialTs.start) / 2.0 + specialTs.start) {
            //move caretOffset to end
            caretOffset = specialTs.end;
          } else {
            caretOffset = specialTs.start;
          }
          return false;
        }
      }
      return true;
    });

    ///tell textInput caretOffset is changed.
    if (caretOffset != selection.baseOffset) {
      value = value.copyWith(
          selection: selection.copyWith(
              baseOffset: caretOffset, extentOffset: caretOffset));
      textInputConnection?.setEditingState(value);
    }
  }
  return value;
}