颤动:当放入列中时,CustomPaint小部件变为空白

时间:2020-07-28 12:51:11

标签: flutter dart custom-painting

我有一些超级奇怪的东西:

以下代码用CustomPaint绘制一个矩形。这个版本工作正常

import 'package:flutter/material.dart';


class MyApp extends StatefulWidget {
  @override
  _ MyAppState createState() => _ MyAppState();
}

class _MyAppState extends State<MyApp> {
  EmbeddedPainter _painter;

  @override
  void initState() {
    super.initState();
    _painter = EmbeddedPainter();
  }

  @override
  Widget build(BuildContext context) {
    return Container(
        child: ClipRect(
          child: CustomPaint(
            painter: _painter
          ),
        ),
    );
  }

}

然后,一旦将此CustomPaint放入Column小部件中,我就不再看到绘制的矩形。

import 'package:flutter/material.dart';


class MyApp extends StatefulWidget {
  @override
  _ MyAppState createState() => _ MyAppState();
}

class _MyAppState extends State<MyApp> {
  EmbeddedPainter _painter;

  @override
  void initState() {
    super.initState();
    _painter = EmbeddedPainter();
  }

  @override
  Widget build(BuildContext context) {
    return Container(
        child: Column(
          children: <Widget>[
              ClipRect(
                child: CustomPaint(
                    painter: _painter
                ),
              ),
          ],
        )
    );
  }

}

画家看起来像这样

class EmbeddedPainter extends CustomPainter with ChangeNotifier {
  var _paint = Paint()
    ..strokeJoin = StrokeJoin.miter
    ..strokeWidth = 1.0
    ..color = Colors.green
    ..style = PaintingStyle.fill;

  @override
  void paint(Canvas canvas, Size size) {
    canvas.drawRect(Rect.fromLTWH(50, 50, 100, 100), _paint);
  }

  @override
  bool shouldRepaint(CustomPainter oldDelegate) => true;

  void update(Color color0, Color color1) {

    // draw
    notifyListeners();
  }
}

1 个答案:

答案 0 :(得分:0)

自己解决:

ClipRect必须用大小为SizedBox的容器包装。


 @override
  Widget build(BuildContext context) {

    return Container(
          child: Column(
            children: <Widget>[
              SizedBox(
                width: 500,
                height: 300,
                child: ClipRect(
                  child: CustomPaint(
                      painter: _painter
                  ),
                ),
              )

            ],
          )
      );
  }