这段代码的作用是在您单击光标时打印光标在文本中的位置。
TextEditingController controller = TextEditingController();
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(
widget.title,
),
),
body: TextField(
controller: controller,
keyboardType: TextInputType.multiline,
maxLines: null,
onTap: () {
int pos = controller.selection.start;
print(
"Position: $pos",
);
},
),
);
}
但问题是这是针对网络的,所以我需要它在光标移动时说出光标的位置,而不仅仅是在我点击它时。我的意思是如果你用键盘移动光标,它也应该打印位置。
我已经尝试过使用 GestureDetector 和 Focus,但什么也没有。知道我可以使用什么吗?
更新:我找到的解决方案如下,它可以完美地满足我的需要:
TextEditingController controller = TextEditingController();
int cursorPosition = 0;
@override
void initState() {
controller.addListener(() {
setState(() {
cursorPosition = controller.selection.base.offset;
print("cursorPosition: $cursorPosition");
});
});
super.initState();
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(
widget.title,
),
),
body: TextField(
controller: controller,
keyboardType: TextInputType.multiline,
maxLines: null,
),
);
}
完整代码:
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: MyHomePage(title: 'Flutter Demo Home Page'),
);
}
}
class MyHomePage extends StatefulWidget {
MyHomePage({Key key, this.title}) : super(key: key);
final String title;
@override
_MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
TextEditingController controller = TextEditingController();
int cursorPosition = 0;
@override
void initState() {
controller.addListener(() {
setState(() {
cursorPosition = controller.selection.base.offset;
print("cursorPosition: $cursorPosition");
});
});
super.initState();
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(
widget.title,
),
),
body: TextField(
controller: controller,
keyboardType: TextInputType.multiline,
maxLines: null,
),
);
}
}