You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Flutter自定义键盘场景下如何获取TextField光标位置并正确输入

自定义键盘光标位置插入问题解决

我需要创建一个禁用系统默认键盘的TextField组件,为此定制了专属键盘,键盘能正常向TextField填充内容,但遇到一个问题:用自定义键盘输入时光标能正常跟随文本;但手动点击文本中间移动光标后,新输入的字符无法插入到光标所在位置。

我的代码

TextField组件代码

InputAtom(
  autofocus: true,
  controller: controllerInput,
  placeholder: "Placeholder",
  fontSize: 35,
  keyboard: TextInputType.none,
  enableInteractiveSelection: true,
  showCursor: true,
  cursorColor: Colors.red,
  enableSuggestions: false,
  autocorrect: false,
),

自定义键盘按钮示例代码

KeyboardButtonAtom.numeric({
    Key? key,
    required String text,
    required TextEditingController controller,
  }): super(
    key: key, 
    text: text,
    controller: controller,
    onPressed: (){
      // 在此添加键盘输入的数字
      controller.text += text.toString();
      // 将光标移至文本末尾
      controller.selection = TextSelection.collapsed(offset: controller.text.length);
      print(controller.selection.baseOffset);
    }
  );

问题:如何在手动点击TextField文本移动光标后,获取光标位置并在该位置插入数字?

解决方法(补充)

在KeyboardButtonAtom中使用以下代码即可解决问题,无论光标处于字符串哪个位置都能正常工作:

String textBeforeCursor = controller.text.substring(0, controller.selection.baseOffset);
String textAfterCursor =  controller.text.substring(controller.selection.extentOffset);
controller.text = textBeforeCursor + text.toString() + textAfterCursor;
int cursorPosition =  textBeforeCursor.length + 1;
controller.selection = TextSelection.collapsed(offset: cursorPosition);

内容的提问来源于stack exchange,提问作者user6551314

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.22 12:30:42