我在flutter中有一个文本字段和一个表情符号选择器按钮。在选择一个表情符号时,我需要将其插入到当前光标位置。我如何才能做到这一点?目前使用TextEditingController
,我只能添加表情符号。我无法获取当前光标偏移量。
emojiPicker() {
return EmojiPicker(
rows: 3,
columns: 7,
recommendKeywords: null,
indicatorColor: flujoAccentColor,
onEmojiSelected: (emoji, category) {
print(emoji);
_messageInputController.text =
_messageInputController.text + emoji.emoji;
}
);
}
发布于 2020-02-04 21:57:21
_txtController.selection
获取选择(或使用选定的表情符号进行光标选择。的选择(或光标位置
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,
),
],
),
),
);
}
}
这样,你不仅可以在光标位置插入选定的表情符号,还可以替换一些选定的文本
发布于 2021-07-01 09:47:53
这是对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),
);
}
笔记
_controller
是一个TextEditingController
.TextEditingValue
,而不是单独更改它们(因为如果您希望光标显示在insert之后,则它们各自都会触发update).TextEditingValue
。发布于 2021-04-09 13:23:49
除了text.replaceRange
,我还有另一个解决方案。
你所需要的是:
TextEditingController _tec;
String youWillAddtoTEC = "your emoji or your clipboard data or else";
String beforeCursorPositionAtTEC = tec.selection.textBefore(tec.text);
String afterCursorPositionAtTEC = tec.selection.textAfter(tec.text);
String result = beforeCursorPositionAtTEC + youWillAddtoTEC + afterCursorPositionAtTEC;
然后将结果添加到tec或您需要的任何小部件中:
tec.text = result;
所选内容或光标位置与上面相同,但如果需要将光标放在"youWillAddToTEC“之后,可以这样做:
tec.selection = TextSelection.collapsed(offset: tec.selection.start + youWillAddtoTEC.lenght);
https://stackoverflow.com/questions/60057840
复制相似问题