我想监听 textEditingController 中光标的变化,但目前监听器只对字符的添加和删除做出反应,有没有办法解决这个问题?
例如在带有 +7 (111) 111-11-11 的 TextField 中,如果用户在“+7”之前设置光标,我想将光标设置回位置 = 3
答案 0 :(得分:0)
我不确定,但这是您想要做的吗?
import 'package:flutter/material.dart';
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return const MaterialApp(
title: 'Demo',
home: MyHomePage(title: 'Demo Home Page'),
);
}
}
class MyHomePage extends StatefulWidget {
const MyHomePage({Key key, this.title}) : super(key: key);
final String title;
@override
_MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
final TextEditingController _controller = TextEditingController();
@override
void initState() {
super.initState();
_controller.addListener(_setPos3);
}
@override
void dispose() {
_controller.dispose();
super.dispose();
}
void _setPos3() {
if (_controller.selection.baseOffset == 0 &&
_controller.selection.extentOffset == 0 &&
3 <= _controller.text.length) {
_controller.value = _controller.value.copyWith(
selection: const TextSelection(baseOffset: 3, extentOffset: 3),
);
}
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(widget.title),
),
body: Center(
child: TextFormField(
controller: _controller,
),
),
);
}
}