Flutter Path.computeMetrics() 的使用注意点

一个Path转虚线的扩展

java 复制代码
extension DashedPathExtension on Path {
  /// 转换为虚线 Path(安全版)
  /// [solidLength]:实线段长度(像素)
  /// [gapLength]:空线段长度(像素)
  /// 返回:新的虚线 Path(原 Path 不变)
  Path toDashedPath({
    required double solidLength,
    required double gapLength,
  }) {
    // 前置参数校验
    assert(solidLength > 0, "实线段长度必须大于0");
    assert(gapLength >= 0, "空线段长度不能为负数");

    // 1. 安全获取 PathMetrics 并校验
    //final PathMetrics metrics = computeMetrics();
    // // 校验1:PathMetrics 为空 → 返回空 Path
    //if (metrics.isEmpty) return Path();

    // 2. 遍历 metrics(兼容多段路径),避免 first 直接报错
    final Path dashedPath = Path();
    for (final PathMetric metric in computeMetrics()) {
      final double totalLength = metric.length;
      // 校验2:单段路径长度为0 → 跳过
      if (totalLength <= 0) continue;

      // 3. 循环绘制实线段(始终从实线开始)
      double currentDistance = 0.0;
      while (currentDistance < totalLength) {
        final double solidEnd = currentDistance + solidLength;
        final double actualEnd = solidEnd > totalLength ? totalLength : solidEnd;

        // 提取实线段并添加到虚线 Path
        final Path segment = metric.extractPath(currentDistance, actualEnd);
        dashedPath.addPath(segment, Offset.zero);

        // 跳过空线段
        currentDistance = solidEnd + gapLength;
      }
    }

    return dashedPath;
  }
}

注意点是这个

js 复制代码
    // 1. 安全获取 PathMetrics 并校验
    // final PathMetrics metrics = computeMetrics();
    // // // 校验1:PathMetrics 为空 → 返回空 Path
    // if (metrics.isEmpty) return Path();

这里调用了 metrics.isEmpty()

js 复制代码
  bool get isEmpty => !iterator.moveNext();

也就是调用了迭代器的moveNext() 再次遍历metrics 就会从第二个元素开始。 如果迭代器本身只有一个元素,这个时候调用metrics.first 救护报错no element。

相关推荐
砖厂小工4 小时前
用 GLM + OpenClaw 打造你的 AI PR Review Agent — 让龙虾帮你审代码
android·github
张拭心5 小时前
春节后,有些公司明确要求 AI 经验了
android·前端·人工智能
张拭心5 小时前
Android 17 来了!新特性介绍与适配建议
android·前端
shankss6 小时前
Flutter 下拉刷新库 pull_to_refresh_plus 设计与实现分析
flutter
Kapaseker7 小时前
Compose 进阶—巧用 GraphicsLayer
android·kotlin
黄林晴7 小时前
Android17 为什么重写 MessageQueue
android
忆江南1 天前
iOS 深度解析
flutter·ios
明君879971 天前
Flutter 实现 AI 聊天页面 —— 记一次 Markdown 数学公式显示的踩坑之旅
前端·flutter
恋猫de小郭1 天前
移动端开发稳了?AI 目前还无法取代客户端开发,小红书的论文告诉你数据
前端·flutter·ai编程
MakeZero1 天前
Flutter那些事-交互式组件
flutter