通过controller控制TextField时,默认状态下光标会跑到内容最前面。
通过以下方式,使光标保持在内容最后面;
class _FormmState extends State<Formm> {
TextEditingController _username = new TextEditingController();
void initState() {
super.initState();
_username.text = "初始值";
}
@override
Widget build(BuildContext context) {
return Container(
height: 600,
child: Column(
children: <Widget>[
TextField(
controller: _username,
decoration: InputDecoration(
icon: Icon(Icons.people),
labelText: "用户名",
helperText: "输入长度2个字以上的汉字",
hintText: "请输入用户名",
errorText: "errorText",
),
onChanged: (value) {
setState(() {
_username.text = value;
_username.value = TextEditingValue(
text: _username.text,
selection: TextSelection.fromPosition(
TextPosition(
affinity: TextAffinity.downstream,
offset: _username.text.length,
),
),
);
});
},
),
Container(
child: TextButton(
child: Text("提交"),
onPressed: () {
print(_username.text);
},
),
)
],
),
);
}
网友评论