Flutter:如何在文本字段文本中间插入文本

Kri*_* CN 4 dart flutter

我有一个颤动的文本字段和一个表情符号选择器按钮。在选择表情符号时,我需要将其插入当前光标位置。我怎样才能做到这一点?目前使用TextEditingController我只能附加表情符号。我无法获得当前的光标偏移量。

emojiPicker() {
    return EmojiPicker(
      rows: 3,
      columns: 7,
      recommendKeywords: null,
      indicatorColor: flujoAccentColor,
      onEmojiSelected: (emoji, category) {
        print(emoji);
        _messageInputController.text =
            _messageInputController.text + emoji.emoji;
     }
    );
  }
Run Code Online (Sandbox Code Playgroud)

Cra*_*Cat 15

  1. 使用_txtController.selection获得的选择(或光标位置)。
  2. 用选定的表情符号替换选择。
  3. 然后固定控制器的选择(或光标位置)
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,
            ),
          ],
        ),
      ),
    );
  }
}
Run Code Online (Sandbox Code Playgroud)

有了这个,你不仅可以在光标位置插入选定的表情符号,还可以替换一些选定的文本


Sur*_*gch 9

这是对 CrazyLazyCat 答案的轻微修改。

void _insertText(String inserted) {
  final text = _controller.text;
  final selection = _controller.selection;
  final newText = text.replaceRange(selection.start, selection.end, inserted);
  _controller.value = TextEditingValue(
    text: newText,
    selection: TextSelection.collapsed(offset: selection.baseOffset + inserted.length),
  );
}
Run Code Online (Sandbox Code Playgroud)

注意事项

  • _controller是一个TextEditingController.
  • 如果您要更改文本和选择,那么您应该使用 aTextEditingValue而不是单独更改它们(因为它们都会触发更新)。
  • 一般来说,如果您插入一些内容,您希望光标出现在插入之后,从而TextSelection.collapsed调整索引。