setValue method

void setValue(
  1. String value
)

Implementation

void setValue(String value) {
  LogUtils.d("text_input", "set value:$value");
  var selectionStart = controller.selection.start;
  var selectionEnd = controller.selection.end;

  LogUtils.d("text_input", "setText: selectionStart:$selectionStart selectionEnd:$selectionEnd");
  var oldValue = controller.text;

  if (value == oldValue) {
    // 不需要重复设置
    return;
  }

  var sub1 = oldValue.substring(0, selectionStart);
  var sub2 = oldValue.substring(selectionEnd);

  LogUtils.d("text_input", "setText: sub1:[$sub1]  sub2:[$sub2]");

  if (selectionStart == selectionEnd &&
      value.length > oldValue.length &&
      value.startsWith(sub1) &&
      value.endsWith(sub2)) {
    // 未选中状态 && insert
    var insertStr = value.substring(selectionStart, value.length - sub2.length);
    LogUtils.d("text_input", "setText: InsertStr: [$insertStr]");
    var offset = selectionStart + insertStr.length;
    if (offset > value.length || offset < 0) {
      offset = value.length;
    }
    controller.value = TextEditingValue(
      text: value,
      selection: TextSelection.fromPosition(
        TextPosition(
          offset: offset,
          affinity: TextAffinity.downstream,
        ),
      ),
    );
  } else if (selectionStart < selectionEnd && value.startsWith(sub1) && value.endsWith(sub2)) {
    // 选中状态 && replace选中部分
    var replaceStr = value.substring(selectionStart, value.length - sub2.length);
    LogUtils.d("text_input", "setText: ReplaceStr: [$replaceStr]");
    var offsetStart = selectionStart;
    var offsetEnd = selectionStart + replaceStr.length;
    if (offsetEnd < 0 || offsetEnd > value.length) {
      offsetEnd = value.length;
    }
    controller.value = TextEditingValue(
      text: value,
      selection: TextSelection(
        baseOffset: offsetStart,
        extentOffset: offsetEnd,
      ),
    );
  } else if (selectionStart == selectionEnd &&
      value.length < oldValue.length &&
      value.endsWith(sub2) &&
      value.startsWith(sub1.substring(0, selectionStart - (oldValue.length - value.length)))) {
    // 未选中状态 && delete
    var delLen = oldValue.length - value.length;
    var offset = selectionEnd - delLen;
    if (offset < 0) {
      offset = 0;
    }
    if (offset > value.length) {
      offset = value.length;
    }
    controller.value = TextEditingValue(
      text: value,
      selection: TextSelection.fromPosition(
        TextPosition(
          offset: offset,
          affinity: TextAffinity.downstream,
        ),
      ),
    );
  } else {
    controller.value = TextEditingValue(
      text: value,
      selection: TextSelection.fromPosition(
        TextPosition(
          offset: value.length,
          affinity: TextAffinity.downstream,
        ),
      ),
    );
  }
}