Flutter:如何在文本字段文本的中间插入文本 [英] Flutter: How to insert text in middle of text field text
本文介绍了Flutter:如何在文本字段文本的中间插入文本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我在Flutter中有一个文本字段和一个表情符号选择器按钮.选择表情符号后,我需要将其插入当前光标位置.我怎样才能做到这一点?当前使用 TextEditingController
,我只能附加表情符号.我无法获得当前光标的偏移量.
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;
}
);
}
推荐答案
- 使用
_txtController.selection
获取选择(或光标位置). - 用选定的表情符号替换所选内容.
- 然后修复控制器的选择(或光标位置)
- Use
_txtController.selection
to get the selection (or cursor position). - replace the selection with selected emoji.
- 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
这篇关于Flutter:如何在文本字段文本的中间插入文本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文