flutter - 在 Flutter 中获取 TextFormField 的选择
问题描述
我的目标是获取 TextFormField 的选定文本,但是每次按下按钮时,TextFormField 都会失去焦点,并且控制台中的打印仅显示 -1 和 -1 之间的选择。
几周前它确实有效,最新版本中的行为是否发生了变化?我在稳定的 Flutter 频道上。( Flutter Channel stable, 2.5.0
)
这是我的测试示例:
import 'package:flutter/material.dart';
class Play extends StatefulWidget {
const Play({Key? key}) : super(key: key);
@override
_PlayState createState() => _PlayState();
}
class _PlayState extends State<Play> {
TextEditingController _controller = TextEditingController();
FocusNode _node = FocusNode();
void _onPressed() {
TextSelection selection = _controller.selection;
print("selection.start: ${selection.start}");
print("selection.end: ${selection.end}");
}
@override
Widget build(BuildContext context) {
return Scaffold(
body: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
TextFormField(
focusNode: _node,
controller: _controller,
),
ElevatedButton(
onPressed: _onPressed,
child: Text("do something"),
),
],
),
);
}
}
解决方案
由于它在移动设备上运行良好,我会说这是 Flutter 中的一个错误,但不要害怕!欢迎来到变通办法和临时解决方案TM的世界;用这个替换你的整个_onPressed
方法:
int start = -1;
int end = -1;
@override
void initState() {
super.initState();
_controller.addListener(() async {
TextSelection selection = _controller.selection;
if (selection.start > -1) start = selection.start;
if (selection.end > -1) end = selection.end;
});
}
void _onPressed() {
print(start);
print(end);
}
如果有什么不是很清楚,请告诉我,我很乐意通过进一步的解释来编辑答案。
Flutter 社区希望您提交错误报告(如果它尚不存在)!:D
推荐阅读
- spring - 如何知道有多少个连接与 SpringBoot 网站连接?
- c++ - 使用 Xcode 和 Eclipse 在 Mac Mojave 上的着色器编译问题
- spring-data-redis - 如何在 Spring-Data-Redis 中为 RedisTemplate 使用连接事件?
- python - 如何在 Python 的 googleapis-common-protos 中使用 proto 文件?
- c++ - 使用指向 class::method 的指针数组调用方法
- azure - 让 Azure DevOps 审查 GitHub 拉取请求
- netlogo - 如何让特定补丁上的海龟做某事
- python - 如何更新模型并对这个对象或其他对象做一些事情?
- python - 为什么设置一个元素值会改变 Python 2d 矩阵中其他元素的值
- html - CSS 网格 + srcset + 尺寸适用于多种宽度和屏幕分辨率?