Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Flutter: How to insert text in middle of text field text

Tags:

flutter

dart

I have a text field in flutter and an emoji picker button. On selecting an emoji I need to insert it at the current cursor position. How can I achieve this? Currently using TextEditingController I'm only able to append the emoji. I'm not able to get the current cursor offset.

emojiPicker() {
    return EmojiPicker(
      rows: 3,
      columns: 7,
      recommendKeywords: null,
      indicatorColor: flujoAccentColor,
      onEmojiSelected: (emoji, category) {
        print(emoji);
        _messageInputController.text =
            _messageInputController.text + emoji.emoji;
     }
    );
  }
like image 933
krishnakumarcn Avatar asked Feb 04 '20 12:02

krishnakumarcn


1 Answers

  1. Use _txtController.selection to get the selection (or cursor position).
  2. replace the selection with selected emoji.
  3. then fix the selection(or cursor position) of the controller
import 'package:emoji_picker/emoji_picker.dart';
import 'package:flutter/material.dart';

void main() {
  runApp(MaterialApp(home: HomePage()));
}

class HomePage extends StatefulWidget {
  @override
  _HomePageState createState() => _HomePageState();
}

class _HomePageState extends State<HomePage> {
  TextEditingController _messageInputController;

  @override
  void initState() {
    _messageInputController = TextEditingController();
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text("Demo"),
      ),
      body: SafeArea(
        child: Column(
          children: <Widget>[
            EmojiPicker(
              rows: 3,
              columns: 7,
              recommendKeywords: null,
              indicatorColor: Colors.red,
              onEmojiSelected: (emoji, category) {
                String text = _messageInputController.text;
                TextSelection textSelection = _messageInputController.selection;
                String newText = text.replaceRange(
                    textSelection.start, textSelection.end, emoji.emoji);
                final emojiLength = emoji.emoji.length;
                _messageInputController.text = newText;
                _messageInputController.selection = textSelection.copyWith(
                  baseOffset: textSelection.start + emojiLength,
                  extentOffset: textSelection.start + emojiLength,
                );
              },
            ),
            TextField(
              controller: _messageInputController,
            ),
          ],
        ),
      ),
    );
  }
}

with this you can not only insert the selected emoji at cursor position, but also can replace some selected text

like image 177
Crazy Lazy Cat Avatar answered Oct 17 '22 06:10

Crazy Lazy Cat