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

Flutter中CustomPaint/SizedBox尺寸异常:指定300宽却为屏幕宽度

问题原因与修复方案

核心问题

你编写的PieChartComponent虽然继承了SizedBox,但在调用父类构造函数时,没有将自定义的width和height参数传递给SizedBox的对应参数。

SizedBox的尺寸由自身的width和height属性控制,你在子类中定义了同名变量,但并未将其传递给父类,导致SizedBox使用默认的null值:

  • 当width为null时,SizedBox会尽可能扩展以填充父组件的可用宽度(也就是你看到的屏幕宽度411);
  • 高度显示为300大概率是父组件的约束巧合,并非代码逻辑正确。

你的测试程序看似正常,实际是同样的问题——只是测试环境中父组件的约束刚好限制了尺寸,属于偶然情况,并非代码逻辑正确。

修复步骤

1. 修正PieChartComponent的构造函数

将自定义的width和height传递给父类SizedBox的构造参数:

class PieChartComponent extends SizedBox {
  final double width;
  final double height;
  PieChartComponent({
    required this.width,
    required this.height,
    required ClassPieChartParams clsPieChartParams,
  }) : super(
          width: width, // 传递width给SizedBox
          height: height, // 传递height给SizedBox
          child: CustomPaint(
            painter: PieChartPainter(
              clsPieChartParams: clsPieChartParams,
            ),
          ),
        );
}

2. 补充PieChartPainter的shouldRepaint方法

当前你的PieChartPainter未实现该方法,会导致饼图数据更新时无法重绘,建议补上:

class PieChartPainter extends CustomPainter {
  final ClassPieChartParams clsPieChartParams;
  PieChartPainter({required this.clsPieChartParams});

  @override
  void paint(Canvas canvas, Size size) {
    debugPrint("\n\n****** At 44: paint: size.width = ${size.width}, size.height = ${size.height}\n");
    // 你的饼图绘制逻辑
  }

  @override
  bool shouldRepaint(covariant PieChartPainter oldDelegate) {
    // 根据参数是否变化决定是否重绘,示例如下:
    return oldDelegate.clsPieChartParams != clsPieChartParams;
  }
}

验证

修改后重新运行,CustomPaint接收到的Size应该会是你指定的300×300,饼图尺寸即可恢复正常。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.27 00:33:33