Flutter:点击自定义AdaptiveTextSelectionToolbar获取选中文本
获取AdaptiveTextSelectionToolbar自定义项的选中文本
要拿到选中的文本,直接通过editableTextState的selection属性获取选中范围,再从原文本里截取对应内容即可。修改你的代码如下:
SelectableText( 'The minimum temperature in Ahmedabad today is likely to hover around 26 degrees Celsius, while the maximum temperature might reach 35 degrees Celsius.', style: const TextStyle( fontWeight: FontWeight.w500, fontSize: 16, color: Colors.black ), contextMenuBuilder: (context, editableTextState) { // 获取原文本内容 final text = editableTextState.textEditingValue.text; // 获取选中的范围 final selection = editableTextState.textEditingValue.selection; return AdaptiveTextSelectionToolbar( anchors: editableTextState.contextMenuAnchors, children: [ InkWell( onTap: () { // 关闭工具栏 editableTextState.hideToolbar(); // 判断是否有选中内容 if (!selection.isCollapsed) { // 截取选中的文本 final selectedText = text.substring(selection.start, selection.end); // 这里写「复制到笔记」的逻辑,比如保存到本地或跳转笔记页面 print('选中的文本:$selectedText'); } }, child: SizedBox( width: 110, child: Center(child: Text(AppStrings.copyToNotes)), ), ), InkWell( onTap: () { // 调用系统默认复制逻辑 editableTextState.copySelection(SelectionChangedCause.toolbar); editableTextState.hideToolbar(); }, child: SizedBox( width: 50, child: Center(child: Text(AppStrings.copy)), ), ) ] ); }, );
关键说明:
- 通过
editableTextState.textEditingValue可获取文本编辑的完整状态,包括原文本和选中范围 selection.isCollapsed用于判断是否有有效选中内容(未选中时start和end位置重合)- 操作完成后调用
hideToolbar()关闭工具栏,优化用户体验 - 系统默认的「复制」功能直接调用
editableTextState.copySelection()实现,无需手动处理剪贴板逻辑
内容的提问来源于stack exchange,提问作者Vishal Thakkar
相关产品推荐
相关产品推荐

