Flutter Textfield Cursor Misplaced Issue

When you would like to enter a Text and display the Text at the same time, you might write the code as below:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
class _MyHomePageState extends State<MyHomePage> {
TextEditingController _textEditingController = TextEditingController();
String displayText;
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(widget.title),
),
body: Center(
child: Padding(
padding: const EdgeInsets.all(30.0),
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
TextField(
controller: _textEditingController,
onChanged: (text) {
setState(() {
_textEditingController.text = text;
});
}),
Text(
_textEditingController.text,
),
],
),
),
),
);
}
}

However, the TextField has an issue that user press the space bar or comma, the cursor automatically placed at the front of the sentence.

In order to fix the issue, you have to use TextEditingController.fromValue as below:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
class _MyHomePageState extends State<MyHomePage> {
TextEditingController _textEditingController = TextEditingController();
String displayText;
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(widget.title),
),
body: Center(
child: Padding(
padding: const EdgeInsets.all(30.0),
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
TextField(
controller: TextEditingController.fromValue(
TextEditingValue(
text: _textEditingController.text,
selection: TextSelection.collapsed(
offset: _textEditingController.text.length,
),
),
),
onChanged: (text) {
setState(() {
_textEditingController.text = text;
});
}),
Text(
_textEditingController.text,
),
],
),
),
),
);
}
}

As you can see below, there is no issue with TextField.

Share