我有一个颤动的文本字段和一个表情符号选择器按钮。在选择表情符号时,我需要将其插入当前光标位置。我怎样才能做到这一点?目前使用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
_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,
),
],
),
),
);
}
}
Run Code Online (Sandbox Code Playgroud)
有了这个,你不仅可以在光标位置插入选定的表情符号,还可以替换一些选定的文本
这是对 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.TextEditingValue而不是单独更改它们(因为它们都会触发更新)。TextSelection.collapsed调整索引。| 归档时间: |
|
| 查看次数: |
3174 次 |
| 最近记录: |