简体   繁体   English

Flutter CustomPaint 未重绘

[英]Flutter CustomPaint is not repainting

I can't make the custom painter repaint.我不能让自定义画家重新粉刷。 I tried to use Listenable, callbacks, setState and nothing repaints the screen.我尝试使用 Listenable、回调、setState 并没有重绘屏幕。

The docs says this:文档是这样说的:

The most efficient way to trigger a repaint is to either:触发重绘的最有效方法是:

  • Extend this class and supply a repaint argument to the constructor of the CustomPainter, where that object notifies its listeners when it is time to repaint.扩展此 class 并向 CustomPainter 的构造函数提供一个重绘参数,其中 object 会在需要重绘时通知其侦听器。
  • Extend Listenable (eg via ChangeNotifier) and implement CustomPainter, so that the object itself provides the notifications directly.扩展 Listenable(例如通过 ChangeNotifier)并实现 CustomPainter,以便 object 本身直接提供通知。 In either case, the CustomPaint widget or RenderCustomPaint render object will listen to the Listenable and repaint whenever the animation ticks, avoiding both the build and layout phases of the pipeline.在任何一种情况下,CustomPaint 小部件或 RenderCustomPaint 渲染 object 都会在 animation 滴答声时侦听可侦听并重新绘制,从而避免管道的构建和布局阶段。

But the code don't work as intended.但是代码没有按预期工作。

This is the code I'm using:这是我正在使用的代码:

import 'package:flutter/gestures.dart';
import 'package:flutter/material.dart';

main() {
  runApp(MaterialApp(
    home: Scaffold(appBar: AppBar(), body: Pad()),
  ));
}

class Pad extends StatefulWidget {
  @override
  _PadState createState() => _PadState();
}

class _PadState extends State<Pad> {
  @override
  Widget build(BuildContext context) {
    final painter = Painter();
    return GestureDetector(
        onTap: () {
          setState(() {
            painter.addY(10);
          });
        },
        child: CustomPaint(
          painter: painter,
          child: Container(),
        ));
  }
}

class Painter extends CustomPainter {
  double y = 10;

  addY(val) {
    y += val;
  }

  @override
  void paint(Canvas canvas, Size size) {
    canvas.drawCircle(Offset(size.width / 2, y++), 100, Paint());
  }

  @override
  bool shouldRepaint(Painter oldDelegate) {
    return true;
  }
}

Listenable works just fine, use ValueNotifier for example, see https://github.com/pskink/matrix_gesture_detector/blob/master/example/lib/custom_painter_demo.dart for some sample code Listenable工作得很好,例如使用ValueNotifier ,请参阅https://github.com/pskink/matrix_gesture_detector/blob/master/example/lib/custom_painter_demo.dart获取一些示例代码

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM