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

人盡茶涼 提交于 2021-02-07 19:32:30

问题


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;
     }
    );
  }

回答1:


  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



来源:https://stackoverflow.com/questions/60057840/flutter-how-to-insert-text-in-middle-of-text-field-text

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!