首页 > 解决方案 > 在颤振中,CustomPaint() 在脚手架/容器小部件中使用时似乎表现得很奇怪

问题描述

所以,我试图在颤动中使用 CustomPaint 小部件在屏幕上绘制一条对角线。在 CustomPaint 小部件中,我正在调用名为 BottomCurvePainter 的 CustomPainter 类。代码是这样的。

class BottomCurvePainter extends CustomPainter {
  @override
  void paint(Canvas canvas, Size size) {
    // TODO: implement paint
    Paint paint = Paint();
    paint.color = Colors.black;
    paint.style = PaintingStyle.stroke;
    paint.strokeWidth = 5.0;

    Path path = Path();
    path.lineTo(size.width, size.height);

    canvas.drawPath(path, paint);
  }

  @override
  bool shouldRepaint(CustomPainter oldDelegate) {
    // TODO: implement shouldRepaint
    //throw UnimplementedError();
    return true;
  }
}

我在家里这样称呼它的方式如下:-

class _MyHomePageState extends State<MyHomePage> {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
          body: Container(
          color: Colors.orange,
          child: CustomPaint(
            painter: BottomCurvePainter(),
          ),
        ),
    );
  }
}

但这似乎不起作用。但是,如果我删除 Scaffold 小部件并直接返回 Container,我可以让它工作,就像这样 -

class _MyHomePageState extends State<MyHomePage> {
  @override
  Widget build(BuildContext context) {
    return Container(
          color: Colors.orange,
          child: CustomPaint(
            painter: BottomCurvePainter(),
          ),
    );
  }
}

有人可以解释为什么将容器包裹在脚手架中不起作用吗?谢谢。

标签: flutterflutter-layout

解决方案


您应该指定容器的宽度和高度属性。它没有出现是因为您没有指定将在脚手架中发生的容器的尺寸(或约束)。从颤振文档中查看容器小部件。


推荐阅读