使用动画和CustomPainter小部件时发生错误

时间:2020-08-19 19:38:56

标签: flutter flutter-animation

你好,我很陌生,正在尝试找出一个错误,但在此问题上我似乎找不到任何东西。下面是我当前的代码:

class Test extends StatefulWidget {
  Test({Key key}) : super(key: key);

  TestState createState() => TestState();
}

class TestState extends State<Test> with SingleTickerProviderStateMixin {
  double circleOneFraction = 0.0;

  Animation<double> circleOneAnimation;
  AnimationController controller;

  @override
  void initState() {
    //width = MediaQuery.of(context).size.width;
    super.initState();
    controller = AnimationController(
        duration: const Duration(milliseconds: 500), vsync: this);
    circleOneAnimation = Tween(begin: 0.0, end: 0.5).animate(controller)
      ..addListener(() {
        setState(() {
          circleOneFraction = circleOneAnimation.value;
        });
      });
    controller.forward();
  }

  @override
  Widget build(BuildContext context) {
    return CustomPaint(
      painter: MyPainter(circleOneFraction),
      child: Container(),
      willChange: true,
      isComplex: true,
    );
  }
}

class MyPainter extends CustomPainter {
  double circleOneFraction;

  MyPainter(this.circleOneFraction);

  @override
  void paint(Canvas canvas, Size size) {
    final heightOfPaint = size.height;
    final widthOfPaint = size.width;

    Paint paint = Paint();

    Path mainBackground = Path();
    mainBackground.addRect(Rect.fromLTRB(0, 0, widthOfPaint, heightOfPaint));
    paint.color = colors.blueColor;
    canvas.drawPath(mainBackground, paint);

    //TEST
    paint.color = Colors.white;
    var circleOneCenter = Offset(0.25 * widthOfPaint, heightOfPaint * 1.1);
    paint.style = PaintingStyle.fill;
    canvas.drawCircle(circleOneCenter, circleOneFraction * widthOfPaint, paint);

    var circleTwoCenter = Offset(0.8 * widthOfPaint, heightOfPaint * 1.1);
    canvas.drawCircle(circleTwoCenter, widthOfPaint * 0.38, paint);
  }

  @override
  bool shouldRepaint(CustomPainter oldDelegate) {
    return null;
  }
}

我想使用CustomPainter小部件在屏幕底部绘制一个扩大的圆圈来制作动画。启动该应用程序时,我每毫秒就会收到一个错误(我认为是刷新背景。我收到的唯一错误消息类型是“断言失败:布尔表达式不能为空”。 我似乎无法用非常无法描述的错误消息找出问题出在哪里。 我希望有人能指出我的错误。

编辑:我确实看到了动画的展开,但是每毫秒都会弹出一个红色错误屏幕。

1 个答案:

答案 0 :(得分:1)

没有像错误的确切输出那样的更多信息,我猜想这是导致错误的函数:

@override
  bool shouldRepaint(CustomPainter oldDelegate) {
    return null; // Returning null instead of a bool. 
  }

此函数的返回应该是布尔值,并且无论函数调用如何,您始终返回null。由于您要覆盖基本函数,因此很可能会在您看不到的代码中调用它,从而导致错误。为该函数何时重绘创建一些有效的逻辑,或者我建议将其默认设置为false;

在Flutter文档中显示的CustomPainter类中的示例返回false。