You need to enable JavaScript to run this app. 如何在Flutter SelectableText组件中添加Find类自定义工具栏选项
优惠活动
大模型
产品
解决方案
定价
更多

如何在Flutter SelectableText组件中添加Find类自定义工具栏选项

Flutter SelectableText 自定义“查找”工具栏实现

目标是在SelectableText的文本选中弹出工具栏中,新增与原生交互风格一致的自定义“查找”操作入口

实现逻辑

Flutter 3.3+ 版本为所有可选择文本组件提供了contextMenuBuilder入口,可完全自定义文本选中后弹出的工具栏选项,不需要修改框架源码,也不需要引入第三方依赖。
SelectableText的contextMenuBuilder回调会在用户触发文本选择工具栏时被调用,传入当前文本选中的区域信息,开发者可基于这些信息自由组装工具栏的按钮列表。

核心代码示例

SelectableText(
  '需要支持查找功能的长文本内容',
  contextMenuBuilder: (context, selectionRegion) {
    return AdaptiveTextSelectionToolbar(
      // 自动适配工具栏的弹出锚点位置,避免错位
      anchors: selectionRegion.contextMenuAnchors,
      children: [
        // 保留系统默认复制功能
        TextSelectionToolbarTextButton(
          padding: TextSelectionToolbarTextButton.getPadding(
            Directionality.of(context),
            0,
          ),
          onPressed: selectionRegion.copyAllEnabled
              ? () => selectionRegion.copySelection(SelectionChangedCause.toolbar)
              : null,
          child: const Text('复制'),
        ),
        // 新增自定义查找按钮
        TextSelectionToolbarTextButton(
          padding: TextSelectionToolbarTextButton.getPadding(
            Directionality.of(context),
            1,
          ),
          onPressed: () {
            // 获取当前选中的文本内容
            final selection = selectionRegion.textEditingValue.selection;
            final selectedText = selectionRegion.textEditingValue.text
                .substring(selection.start, selection.end);
            
            Navigator.pop(context); // 关闭弹出的工具栏
            // 自定义查找逻辑:跳转搜索页、弹出匹配结果浮层等
            triggerSearchAction(selectedText);
          },
          child: const Text('查找'),
        ),
      ],
    );
  },
)

实操注意点

  • 使用AdaptiveTextSelectionToolbar组件组装工具栏时,会自动匹配对应平台的原生样式,不需要手动调整圆角、阴影、字体大小等视觉参数
  • 按钮在工具栏中的排列顺序与children列表顺序一致,可根据需求调整“查找”按钮在工具栏中的位置
  • 当前选中文本的范围、内容不需要手动维护,回调传入的selectionRegion对象会实时同步文本的选中状态,和系统默认工具栏的数据源完全一致
  • 低于3.3版本的Flutter,可通过重写SelectionArea的工具栏构造逻辑实现相同效果,核心的按钮组装、事件绑定逻辑没有差异

内容的提问来源于stack exchange,提问作者Naimur Hasan

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.11.01 02:54:03