You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.07 16:03:18