captureWidget method
Captures a widget as an image using its global key.
Returns a high-resolution image of the widget bounded by RenderRepaintBoundary for smooth animation rendering.
Implementation
Future<ui.Image?> captureWidget(BuildContext context, GlobalKey key) async {
RenderRepaintBoundary boundary =
key.currentContext!.findRenderObject() as RenderRepaintBoundary;
// If some animation is currently running in target object or whenever
// needsPaint is true, wait for end of frame to start capturing widget.
if (boundary.debugNeedsPaint) {
const int maxRetries = 5;
for (int i = 0; i < maxRetries; i++) {
await WidgetsBinding.instance.endOfFrame;
if (!context.mounted) return null;
if (!boundary.debugNeedsPaint) break;
}
// If it's still painting, we can't capture it.
if (boundary.debugNeedsPaint) {
if (kDebugMode) {
debugPrint(
'HeroContainer: Failed to capture widget after $maxRetries retries.',
);
}
return null;
}
}
// Convert to image with device pixel ratio for high resolution.
ui.Image image = await boundary.toImage(
pixelRatio: MediaQuery.of(context).devicePixelRatio,
);
return image;
}