Flutter SelectableText.rich实现文本选中之后显示操作菜单按钮

直接先看需求图


image.png

这个选中有很多部件都可以实现,比如TextField、SelectableText、SelectableText.rich

看看它们选中后的默认效果,
image.png

image.png

很显然这不是我们想要的,我们需要自定义布局

后发现他们都提供了contextMenuBuilder方法,以及onSelectionChanged,对比发现contextMenuBuilder比较合适 ,因为返回了选中范围的起始坐标。

我这里使用SelectableText.rich,另外两个部件可自行测试

一开始,我发现提供了AdaptiveTextSelectionToolbar标准部件

AdaptiveTextSelectionToolbar(
                anchors: editableTextState.contextMenuAnchors,
                children: [
                  _buildMenuItem(Icons.copy, '复制', () {
                    _copyText(context, editableTextState);
                  }),
                  _buildMenuItem(Icons.border_color, '画线', () {
                    _underlineText(context, editableTextState);
                  }),
                  _buildMenuItem(Icons.auto_awesome, 'AI搜索', () {
                    _callAI(context, editableTextState);
                  }),
                  _buildMenuItem(Icons.book, '笔记', () {
                    _saveNote(context, editableTextState);
                  }),
                ],
              );

Widget _buildMenuItem(IconData icon, String text, VoidCallback onTap) {
    return GestureDetector(
      onTap: onTap,
      child: Padding(
        padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 1),
        child: Column(
          mainAxisSize: MainAxisSize.min,
          children: [
            Icon(icon, size: 18, color: Colors.black87),
            SizedBox(height: 2),
            Text(text, style: TextStyle(fontSize: 14, color: Colors.black87)),
          ],
        ),
      ),
    );
  }

效果


image.png

这个位置是没问题,图标和文本也修改了,但是 背景色,圆角,和小三角呢?研究发现AdaptiveTextSelectionToolbar没有提供其他修改的方法,只要放弃了标准部件

我直接返回一个横向的布局呢?

结构:Stack>Container>row>,这样发现按钮直接出现在屏幕的左上角,那怎么和AdaptiveTextSelectionToolbar一样显示在对应的位置呢
我们来看看 contextMenuBuilder: (context, editableTextState) {},其中editableTextState就包含了位置相关的信息

  var endX=editableTextState.contextMenuAnchors.primaryAnchor.dx;
  var endY=editableTextState.contextMenuAnchors.primaryAnchor.dy;
  var startX=editableTextState.contextMenuAnchors.secondaryAnchor!.dx;
  var centerX=startX+(endX-startX)/2;

有这些坐标,我以为就大功告成了,后面发现位置不对,因为你的布局也是有宽高的,你需要知道你布局的宽高,减掉一半才可以完成居中定位
后面发现 ,菜单布局的宽高不好获取,因为你需要渲染完成才可以获取widget的宽高,但是我们需要定位,就需要再渲染之前计算位置,那咋整呢,后面想了下,在contextMenuBuilder方法中,延时一下获取

        Timer(Duration(milliseconds: 1),(){
                    if(size.width==0)
                    _getWidgetSize();
                  });

果然可以了,


image.png

不过紧接着又发现问题了,如果选择范围比较窄,又刚好在上下左右边缘,会显示不全,


image.png

image.png

后面调整如下(具体算法放在offsetX方法中)
image.png

image.png

image.png

,最后就差倒三角了,写一个TrianglePainter类

import 'package:flutter/material.dart';

class TrianglePainter extends CustomPainter {
  final bool isInverted;

  TrianglePainter({this.isInverted = true});

  @override
  void paint(Canvas canvas, Size size) {
    final paint = Paint()
      ..color = Colors.black87
      ..style = PaintingStyle.fill;

    final path = Path();
    if (isInverted) {
      // 绘制倒三角形
      path.moveTo(0, 0);
      path.lineTo(size.width / 2, size.height);
      path.lineTo(size.width, 0);
    } else {
      // 绘制正三角形
      path.moveTo(size.width / 2, 0);
      path.lineTo(0, size.height);
      path.lineTo(size.width, size.height);
    }
    path.close();

    canvas.drawPath(path, paint);
  }

  @override
  bool shouldRepaint(covariant CustomPainter oldDelegate) => false;
}

最终效果:


image.png

image.png

完整代码就两三个类

class Selectable extends StatefulWidget {
  const Selectable({super.key});

  @override
  State<Selectable> createState() => _SelectableState();
}

class _SelectableState extends State<Selectable> {
  final GlobalKey _key = GlobalKey();
  Size size=Size(0, 0);
  TextSpan textSpan=TextSpan(text: '美乌代表团还讨论了人道主义努力作为和平进程一部分的重要性,特别是在停火期间,'
      '包括交换战俘、释放被拘留的平民以及帮助被迫流离失所的乌克兰儿童返回等。'
      '双方代表团同意确定谈判团队组成并立即开始谈判,'
      '以实现持久和平并确保乌克兰的长期安全。'
      '美国承诺与俄罗斯代表讨论这些具体建议。乌克兰代表团再次强调,欧洲伙伴应该参与和平进程。'
      '两国总统同意尽快就乌克兰关键矿产资源开发达成全面协议,以增强乌克兰经济并确保乌克兰的长期繁荣与安全。'
      '当天乌克兰总统办公室主任叶尔马克表示,'
      '美国和乌克兰朝着恢复乌克兰可持续和平迈出了重要步伐。'
      '两国代表一致认为现在是开始建立持久和平进程的时候了。');

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    WidgetsBinding.instance.addPostFrameCallback((_) {
      _getWidgetSize();
    });
  }

  void _getWidgetSize() {
    final RenderBox? box = _key.currentContext?.findRenderObject() as RenderBox?;
    if (box != null) {
      setState(() {
        size=box.size;
      });
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: SafeArea(
        child: Container(
          margin: EdgeInsets.all(10),
          padding: EdgeInsets.all(10),
          decoration: BoxDecoration(
            borderRadius: BorderRadius.circular(10),
            border: Border.all(color: Colors.blue, width: 2),
          ),
          child: SelectableText.rich(
              textSpan,
              style: TextStyle(fontSize: 16),
              contextMenuBuilder: (context, editableTextState) {
                return SelectMenuWidget(
                  maxSize: size,
                  editableTextState: editableTextState,
                  onSelect: (int index) {
                    if (index == 0) {
                      _copyText(context, editableTextState);
                    } else if (index == 1) {
                      _underlineText(context, editableTextState);
                    }else if (index == 2) {
                      _callAI(context, editableTextState);
                    }else if (index == 3) {
                      _saveNote(context, editableTextState);
                    }
                  },
                );
              }),
        ),
      ),
    );
  }

  /// 复制选中的文本
  void _copyText(BuildContext context, EditableTextState editableTextState) {
    String selectedText =
        editableTextState.textEditingValue.selection.textInside(editableTextState.textEditingValue.text);
    Clipboard.setData(ClipboardData(text: selectedText));
    ScaffoldMessenger.of(context).showSnackBar(SnackBar(content: Text('已复制')));
    editableTextState.hideToolbar();
  }

  /// 已添加下划线
  void _underlineText(BuildContext context, EditableTextState editableTextState) {
    // 获取当前的选中范围
    TextSelection selection = editableTextState.textEditingValue.selection;
    if (editableTextState.textEditingValue.text.isEmpty) {
      ScaffoldMessenger.of(context).showSnackBar(SnackBar(content: Text('没有选中文本')));
      return;
    }

    // 获取当前的文本
    String currentText = editableTextState.textEditingValue.text;
    // 确保选中部分的文本范围有效
    String selectedText = currentText.substring(selection.start, selection.end);
    // 更新 TextEditingController 或相应的文本显示方式
    setState(() {
      textSpan=getUnderlineTextSpan(selectedText,selection.start,selection.end);
    });

    // 这里通过 EditableTextState 来刷新
    editableTextState.showToolbar();
    ScaffoldMessenger.of(context).showSnackBar(SnackBar(content: Text('已添加下划线')));
  }

  TextSpan getUnderlineTextSpan(String text,int start,int end){
    // 创建下划线样式的文本
    TextSpan underlinedText = TextSpan(
      text: text,
      style: TextStyle(
        decoration: TextDecoration.underline, // 添加下划线
      ),
    );

    // 重新构建新的 TextSpan
    TextSpan updatedTextSpan = TextSpan(
      children: [
        TextSpan(text: text.substring(0, start)), // 选中前的文本
        underlinedText, // 选中的部分添加下划线
        TextSpan(text: text.substring(end)), // 选中后的文本
      ],
    );
    return updatedTextSpan;
  }

  /// 调用AI分析功能
  void _callAI(BuildContext context, EditableTextState editableTextState) {
    ScaffoldMessenger.of(context).showSnackBar(SnackBar(content: Text('AI法师已启动')));
    editableTextState.hideToolbar();
  }

  /// 保存笔记功能
  void _saveNote(BuildContext context, EditableTextState editableTextState) {
    ScaffoldMessenger.of(context).showSnackBar(SnackBar(content: Text('禅师笔录已添加')));
    editableTextState.hideToolbar();
  }
}
class SelectMenuWidget extends StatefulWidget {
  EditableTextState editableTextState;
  Function(int) onSelect;
  Size maxSize;
  SelectMenuWidget({super.key,required this.editableTextState,required this.onSelect,required this.maxSize});

  @override
  State<SelectMenuWidget> createState() => _SelectMenuWidgetState(editableTextState: editableTextState,onSelect: onSelect);
}


class _SelectMenuWidgetState extends State<SelectMenuWidget> {
  EditableTextState editableTextState;
  Function(int) onSelect;
  _SelectMenuWidgetState({required this.editableTextState,required this.onSelect});

  double get endX=> editableTextState.contextMenuAnchors.primaryAnchor.dx;
  double get endY=> editableTextState.contextMenuAnchors.primaryAnchor.dy;

  double get startX=>editableTextState.contextMenuAnchors.secondaryAnchor!.dx;

  double get centerX=> startX+(endX-startX)/2;

  final GlobalKey _menuKey = GlobalKey();
  Size size=Size(0, 0);
  Size triangleSize=Size(20, 10);

  Size _getMenuSize() {
    final RenderBox? box = _menuKey.currentContext?.findRenderObject() as RenderBox?;
    if (box != null) {
      return box.size;
    }
    return Size.zero;
  }

  var menus= ["复制","画线","笔记","AI搜索"];
  var icons= [Icons.copy,Icons.border_color,Icons.book,Icons.search];

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    WidgetsBinding.instance.addPostFrameCallback((_) {
      if(size.width==0)
        setState(() {
          size=_getMenuSize();
        });
    });

  }

  @override
  Widget build(BuildContext context) {
    return  Stack(
      children: [
        Positioned(
          top:endY<50? endY+30: endY-size.height-triangleSize.height,
          // left: centerX-size.width/2, 不能一直取中间,否则中心点在两侧,菜单就显示不全
          left: centerX-size.width/2-offsetX(),
          child: Container(
            key: _menuKey,
            padding: EdgeInsets.all(8),
            decoration: BoxDecoration(
              color: Colors.black87,
              borderRadius: BorderRadius.circular(8),
            ),
            child: Row(
              children:List.generate(menus.length, (index){
                return _buildMenuItem(icons[index], menus[index], (){
                  onSelect(index);
                });
              }),
            ),
          ),
        ),
        Positioned(
            top:endY<50? endY+20: endY-triangleSize.height,
            left:centerX -triangleSize.width/2,
            child: CustomPaint(
              size: triangleSize,
              painter: TrianglePainter(isInverted: endY<50?false: true),
            )
        )
      ],
    );
  }

  double offsetX(){
    if(centerX<size.width/2){
      return centerX-size.width/2;
    }else if(widget.maxSize.width-centerX<size.width/2){
      return size.width/2-(widget.maxSize.width-centerX)-10;
    }else return 0;
  }

  Widget _buildMenuItem(IconData icon, String text, VoidCallback onTap) {
    return InkWell(
      onTap: onTap,
      child: Padding(
        padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 1),
        child: Column(
          mainAxisSize: MainAxisSize.min,
          children: [
            Icon(icon, size: 18, color: Colors.white),
            SizedBox(height: 2),
            Text(text, style: TextStyle(fontSize: 14, color: Colors.white)),
          ],
        ),
      ),
    );
  }
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 230,501评论 6 544
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 99,673评论 3 429
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 178,610评论 0 383
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 63,939评论 1 318
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 72,668评论 6 412
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 56,004评论 1 329
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 44,001评论 3 449
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 43,173评论 0 290
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 49,705评论 1 336
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 41,426评论 3 359
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 43,656评论 1 374
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 39,139评论 5 364
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 44,833评论 3 350
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 35,247评论 0 28
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 36,580评论 1 295
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 52,371评论 3 400
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 48,621评论 2 380

推荐阅读更多精彩内容

  • CSS 是什么 css(Cascading Style Sheets),层叠样式表,选择器{属性:值;属性:值}h...
    崔敏嫣阅读 1,507评论 0 5
  • 本文介绍如何使用 OpenGL ES 来实现大长腿拉伸的功能。先看下拉伸前后的效果对比图: 我们首先来分析一下该图...
    Maji1阅读 1,047评论 0 0
  • 本文主要讲述页面布局样式方面涉及的知识点,更全面的对CSS相应的技术进行归类、整理、说明,没有特别详细的技术要点说...
    Joel_zh阅读 888评论 0 1
  • 引用CSS方式 内部引用 html文件中写一个 标签,并将样式写入到里面,举例: 外部引用 通过 标签实现,里面有...
    dawsonenjoy阅读 470评论 0 0
  • 相较于 iOS 上火热的开发势头,macOS 开发简直就是一片蓝海。让人不禁有些好奇,本是同根生的 macOS 开...
    davidleee阅读 6,268评论 6 9