i want to add text in click of my button into text field but problem is it's add text in end of the textfield value i want to add text where user want to add text in middle of text field or any where .. i try :
TextEditingController symbolTextField = TextEditingController();
symbolTextField.text =
symbolTextField.text + items[index];
but my items value is add in end of the textfield value
Solution 1: Spike L
Make use of controller.selection
, I created a example for you:
class _MyHomePageState extends State<MyHomePage> {
TextEditingController controller;
@override
void initState() {
super.initState();
controller = TextEditingController();
}
@override
void dispose() {
controller.dispose();
super.dispose();
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(widget.title),
),
body: Center(
child: Row(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Expanded(
child: TextField(
controller: controller,
),
),
ElevatedButton(
onPressed: () => insert("SSS"),
child: Text('Add "SSS"'),
),
],
),
),
);
}
void insert(String content) {
var text = controller.text;
var pos = controller.selection.start;
controller.value = TextEditingValue(
text: text.substring(0, pos) + content + text.substring(pos),
selection: TextSelection.collapsed(offset: pos + content.length),
);
}
}