0

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

example video:

2 Answers 2

2

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),
    );
  }
}
Sign up to request clarification or add additional context in comments.

2 Comments

'SSS' is text which placed in text field?
Yes, i edited the souce to make it more clear
0

The right way to do this is

TextField(
  decoration: InputDecoration(
      prefixIcon: Padding(
            padding: const EdgeInsets.only(left: 20, right: 10),
            child: Icon(
              Icons.search,
            ),
          ),
      suffixIcon: Padding(
            padding: const EdgeInsets.only(left: 20, right: 10),
            child: Icon(
              Icons.close,
            ),
          ),
   ),
);

you can place any widget there button or anything

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.