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

Flutter自定义Tooltip形状:如何缩短箭头长度?

解决Flutter Tooltip自定义箭头缩短问题

需要在Flutter中实现如图所示的自定义形状边框,并将其应用于Tooltip的ShapeDecoration。目前已编写了ToolTipCustomShape类代码,但需要缩短箭头长度,具体修改方法如下:

自定义Tooltip形状效果图

原代码

class ToolTipCustomShape extends ShapeBorder {
  final bool usePadding;

  const ToolTipCustomShape({this.usePadding = true});

  @override
  EdgeInsetsGeometry get dimensions =>
      EdgeInsets.only(bottom: usePadding ? 20 : 0);

  @override
  Path getInnerPath(Rect rect, {TextDirection? textDirection}) => Path();

  @override
  Path getOuterPath(Rect rect, {TextDirection? textDirection}) {
    rect =
        Rect.fromPoints(rect.topLeft, rect.bottomRight - const Offset(0, 20));
    return Path()
      ..addRRect(
          RRect.fromRectAndRadius(rect, Radius.circular(rect.height / 1)))
      ..moveTo(rect.bottomCenter.dx + 90 , rect.bottomCenter.dy)
      ..relativeLineTo(10, 20)
      ..relativeLineTo(10, -20)
      ..close();
  }

  @override
  void paint(Canvas canvas, Rect rect, {TextDirection? textDirection}) {}

  @override
  ShapeBorder scale(double t) => this;
}

修改方法

箭头的垂直长度由relativeLineTo方法的第二个参数控制,原代码中箭头垂直长度为20,只需将这个数值改小即可缩短箭头。同时要保持箭头对称,两个relativeLineTo中的垂直偏移量需正负对应且绝对值一致。

另外要同步调整容器底部偏移和Tooltip的底部内边距,避免内容区域与箭头重叠。

修改后的代码示例

class ToolTipCustomShape extends ShapeBorder {
  final bool usePadding;

  const ToolTipCustomShape({this.usePadding = true});

  @override
  EdgeInsetsGeometry get dimensions =>
      // 同步修改底部内边距,与箭头长度匹配
      EdgeInsets.only(bottom: usePadding ? 12 : 0);

  @override
  Path getInnerPath(Rect rect, {TextDirection? textDirection}) => Path();

  @override
  Path getOuterPath(Rect rect, {TextDirection? textDirection}) {
    // 调整容器底部位置,与箭头长度一致
    rect =
        Rect.fromPoints(rect.topLeft, rect.bottomRight - const Offset(0, 12));
    return Path()
      ..addRRect(
          RRect.fromRectAndRadius(rect, Radius.circular(rect.height / 1)))
      ..moveTo(rect.bottomCenter.dx + 90 , rect.bottomCenter.dy)
      // 将箭头垂直长度从20改为12,可按需调整数值
      ..relativeLineTo(10, 12)
      ..relativeLineTo(10, -12)
      ..close();
  }

  @override
  void paint(Canvas canvas, Rect rect, {TextDirection? textDirection}) {}

  @override
  ShapeBorder scale(double t) => this;
}

补充说明

  • 若要调整箭头宽度,可修改relativeLineTo的第一个参数(比如把10改成8,箭头会更窄)
  • 箭头长度的数值可根据视觉需求自由调整,保持正负值绝对值一致即可

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.09 10:25:07