dreampad/lib/app/shared/widgets/widgets_to_image.dart
2023-11-28 10:45:09 +08:00

49 lines
1.3 KiB
Dart

import 'package:flutter/material.dart';
import 'dart:typed_data';
import 'package:flutter/rendering.dart';
import 'dart:ui' as ui;
class WidgetsToImage extends StatelessWidget {
final Widget? child;
final WidgetsToImageController controller;
const WidgetsToImage({
Key? key,
required this.child,
required this.controller,
}) : super(key: key);
@override
Widget build(BuildContext context) {
/// to capture widget to image by GlobalKey in RepaintBoundary
return RepaintBoundary(
key: controller.containerKey,
child: child,
);
}
}
class WidgetsToImageController {
GlobalKey containerKey = GlobalKey();
/// to capture widget to image by GlobalKey in RenderRepaintBoundary
Future<Uint8List?> capture() async {
try {
/// boundary widget by GlobalKey
RenderRepaintBoundary? boundary = containerKey.currentContext
?.findRenderObject() as RenderRepaintBoundary?;
// double dpr = ui.window.devicePixelRatio;
/// convert boundary to image
final image = await boundary!.toImage(pixelRatio: 2.0);
/// set ImageByteFormat
final byteData = await image.toByteData(format: ui.ImageByteFormat.png);
final pngBytes = byteData?.buffer.asUint8List();
return pngBytes;
} catch (e) {
rethrow;
}
}
}