flutter controller 下的TextEditingController出现光标位置定位问题

之前一直在使用TextField对进行赋值的时候,发现controller会经常用到然后将他封装到了一个类当中,代码如下:

static TextEditingController inputTextCollection(String value) {
    return TextEditingController.fromValue(TextEditingValue(
        text: value,
        //让光标保持在最后
        selection: TextSelection.fromPosition(TextPosition(
            affinity: TextAffinity.downstream, offset:value==""?0:value.length))
    ));
  }

然后发现如果需要修改中间的内容时,光标也会跑到最后当中去,然后查了查官方文档发现下面这样写可以解决光标位置在最后的问题。然后发现也不行,后来看到提示

Text selection index was clamped (-1->0) to remain in bounds. This may not be your fault, as some keyboards may select outside of bounds.

进行了这行代码,就可以搞定:
String value=”1234“; //需要保存的值
TextEditingController inputTextCollection(String value) {
TextEditingController tempController = TextEditingController();
//解决设置了初始值之后,
tempController.addListener(() {
final text =tempController.text;
tempController.value = tempController.value.copyWith(
text: text,
selection: TextSelection(baseOffset: text.length, extentOffset: text.length),
composing: TextRange.empty,
);
});
tempController.text = value;
return tempController;
}

TextField(
controller:inputTextCollection(value)

原文地址:
https://stackoverflow.com/questions/60047389/text-selection-index-was-clamped-1-0-to-remain-in-bounds-in-my-description


版权声明:本文为qq_19587639原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。