You need to enable JavaScript to run this app. Flutter中使用CustomPaint绘制圆弧加载器时Canvas无显示
优惠活动
大模型
产品
解决方案
定价
更多

Flutter中使用CustomPaint绘制圆弧加载器时Canvas无显示

代码存在的核心问题
  • 全链路缺少有限尺寸约束:从外层Container、Stack到最终的CustomPaint没有指定任何宽高约束,在无界约束场景下CustomPaint会将自身尺寸强制设为0,结合你写的矩形计算逻辑,最终生成的绘制矩形大小为0,完全没有可绘制的区域,自然看不到任何显示。
  • 重绘逻辑完全失效:shouldRepaint方法固定返回false,哪怕动画驱动的radius参数持续变化,CustomPaint也不会触发重绘流程,画笔只在初始化时执行一次,后续的参数变化完全不会体现在绘制结果上。
  • 矩形计算逻辑错位:你定义的radius参数本意是控制圆弧本身的尺寸,代码里却把绘制矩形的宽高写成了size.width / radius、size.height / radius,既没有将传入的半径参数作为圆弧尺寸的依据,反而让矩形尺寸和传入参数形成反向缩放,完全违背了参数的设计初衷。
  • 圆弧扫掠角度逻辑别扭:drawArc的第三个参数是沿顺时针方向的扫掠角度,传入负值会沿逆时针方向绘制,和预期的双圆弧旋转Loader形态存在偏差,可读性也很差。
修正后的可运行代码

首先调整ArcPainter实现,匹配参数语义、修复重绘逻辑:

class ArcPainter extends CustomPainter {
  final double radius;
  ArcPainter({
    this.radius = 20,
  });

  @override
  void paint(Canvas canvas, Size size) {
    Paint paint = Paint()
      ..color = Colors.black
      ..strokeWidth = 5.0
      ..strokeCap = StrokeCap.round
      ..style = PaintingStyle.stroke;
    // 直接以传入的radius为核心参数生成绘制矩形,和参数语义匹配
    Rect rect = Rect.fromCenter(
        center: size.center(Offset.zero),
        width: radius * 2,
        height: radius * 2);
    // 两个圆弧中心对称,顺时针扫掠90度,形成标准的双段圆弧Loader形态
    canvas.drawArc(rect, pi / 4, pi / 2, false, paint);
    canvas.drawArc(rect, pi / 4 + pi, pi / 2, false, paint);
  }

  @override
  bool shouldRepaint(ArcPainter old) {
    // 仅当radius参数变化时触发重绘,避免不必要的性能损耗
    return old.radius != radius;
  }
}

然后调整调用侧,给组件加上明确的尺寸约束,去掉冗余的布局层级:

Widget build(BuildContext context) {
  return Material(
    child: Center(
      child: Container(
        // 给容器设置固定宽高,解决无约束导致的CustomPaint尺寸为0的问题
        width: 120,
        height: 120,
        child: AnimatedBuilder(
          animation: _animationController,
          builder: (context, child) {
            return Transform.rotate(
              angle: _animationController.value * 4.0 * pi,
              child: CustomPaint(
                // 把动画值映射为圆弧的实际半径,实现缩放+旋转的加载效果
                painter: ArcPainter(radius: _animation.value * 10),
              ),
            );
          },
        ),
      ),
    ),
  );
}

内容的提问来源于stack exchange,提问作者Cyrus the Great

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.11.15 08:36:01