我在 flutter
应用程序中有一个 text field
旨在让用户编辑数据。当 TextField 出现时,它已经包含了数据,这工作正常。问题在于,当用户将光标放在 TextField 的末尾或其中的任何位置并开始键入时,光标会移回开头,有时会删除第一个或两个单词。
我试过将对 Controller 的函数调用放在 setState 中,但这没有帮助。如果我根本不使用 Controller ,问题就会消失,但在他们点击框外后我无法保存他们的输入。
这是文本字段的代码,它正在更改
TextField(
decoration: InputDecoration(
border: InputBorder.none
),
controller: controller,
autofocus: true,
onChanged: (text) {
controller..text = text;
controller..selection = TextSelection.collapsed(offset: controller.text.length);
},
maxLines: 8,
here's where I create the controller
TextEditingController controller = new TextEditingController();
controller.text = *initial text here*;
here's flutter doctor
[√] Flutter (Channel stable, v1.5.4-hotfix.2, on Microsoft Windows [Version 10.0.17134.829], locale en-US)
• Flutter version 1.5.4-hotfix.2 at C:\Users\jhall\Desktop\flutter
• Framework revision 7a4c33425d (9 weeks ago), 2019-04-29 11:05:24 -0700
• Engine revision 52c7a1e849
• Dart version 2.3.0 (build 2.3.0-dev.0.5 a1668566e5)
[√] Android toolchain - develop for Android devices (Android SDK version 28.0.3)
• Android SDK at C:\Users\jhall\AppData\Local\Android\sdk
• Android NDK location not configured (optional; useful for native profiling support)
• Platform android-Q, build-tools 28.0.3
• Java binary at: C:\Program Files\Android\Android Studio1\jre\bin\java
• Java version OpenJDK Runtime Environment (build 1.8.0_152-release-1343-b01)
• All Android licenses accepted.
[√] Android Studio (version 3.4)
• Android Studio at C:\Program Files\Android\Android Studio1
• Flutter plugin version 35.3.1
• Dart plugin version 183.6270
• Java version OpenJDK Runtime Environment (build 1.8.0_152-release-1343-b01)
[√] VS Code, 64-bit edition (version 1.24.1)
• VS Code at C:\Program Files\Microsoft VS Code
• Flutter extension version 2.21.1
[√] Connected device (1 available)
• Android SDK built for x86 • emulator-5554 • android-x86 • Android 9 (API 28) (emulator)
• No issues found!
所以我基本上只需要您期望从文本输入字段获得的正常功能,以便用户能够将光标放在他们喜欢的任何地方并键入。
我已经尝试一起摆脱 on Change,但问题仍然存在。
最佳答案
你不必做
controller..text = text;
在 onChanged
中,因为 Controller 的文本会在您将其连接到 TextField 后自动更改。
原因是一旦您将一些文本设置为 controller
,它就会重新应用
文本,从而将光标移动到前面。
在你的情况下:
TextField(
decoration: InputDecoration(
border: InputBorder.none
),
controller: controller,
autofocus: true,
onChanged: (text) {},
maxLines: 8,
)
应该可以解决问题。
关于Flutter 如何让文本字段中的光标停止移动到开头?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56872752/