如何通知子树中发生了重绘?

Ale*_*uin 5 flutter

ui.Image每次重新绘制小部件或其子项时,我都需要拍摄小部件的快照(以生成)。

为了拍摄小部件的快照,我使用了 a RepaintBoundary,它使用一种方法正确生成了图像_captureImage

如何通知我子树中发生了重绘,以便_captureImage仅在需要时(即每次子树的视觉表示发生变化时)调用?

这是我当前小部件的简化版本。

class AutoSnapshotWidget extends StatefulWidget {
  const AutoSnapshotWidget({
    Key? key,
    required this.child,
    required this.onChange,
  }) : super(key: key);

  final Widget child;
  final void Function(ui.Image) onChange;

  @override
  State<AutoSnapshotWidget> createState() => _AutoSnapshotWidgetState();
}

class _AutoSnapshotWidgetState extends State<AutoSnapshotWidget> {
  final _key = GlobalKey();

  // *****************************************************************
  // How to make this function called every time the child is repaint?
  // *****************************************************************  
  void _captureImage() async {
    final buildContext = _key.currentContext! as SingleChildRenderObjectElement;
    final boundary = buildContext.findRenderObject()! as RenderRepaintBoundary;
    final image = await boundary.toImage();
    widget.onChange(image);
  }

  @override
  Widget build(BuildContext context) {
    return RepaintBoundary(
      key: _key,
      child: widget.child,
    );
  }
}
Run Code Online (Sandbox Code Playgroud)

Zac*_*Zac 0

如果您愿意,您可以在每次小部件重建完成时拍摄快照。WidgetsBinding.instance.addPostFrameCallback()通过编辑您的方法来做到这一点,如下build所示:

  @override
  Widget build(BuildContext context) {
    WidgetsBinding.instance
        .addPostFrameCallback((_) => _captureImage());
    return RepaintBoundary(
      key: _key,
      child: widget.child,
    );
  }
Run Code Online (Sandbox Code Playgroud)