xxxxxxxxxx
import 'dart:io';
import 'dart:ui' as ui;
import 'package:flutter/rendering.dart';
import 'package:path_provider/path_provider.dart';
Future<void> takeScreenshotOfWidget(GlobalKey widgetKey) async {
try {
RenderRepaintBoundary boundary = widgetKey.currentContext.findRenderObject();
ui.Image image = await boundary.toImage(pixelRatio: 3.0);
final directory = (await getApplicationDocumentsDirectory()).path;
ByteData byteData = await image.toByteData(format: ui.ImageByteFormat.png);
Uint8List pngBytes = byteData.buffer.asUint8List();
File screenshotFile = File('$directory/screenshot.png');
await screenshotFile.writeAsBytes(pngBytes);
print('Screenshot taken! Saved to: ${screenshotFile.path}');
} catch (e) {
print('Error capturing screenshot: $e');
}
}
xxxxxxxxxx
class PngHome extends StatefulWidget {
const PngHome({super.key});
@override
State<PngHome> createState() => _PngHomeState();
}
class _PngHomeState extends State<PngHome> {
GlobalKey globalKey = GlobalKey();
Future<void> _capturePng() async {
final RenderRepaintBoundary boundary = globalKey.currentContext!.findRenderObject()! as RenderRepaintBoundary;
final ui.Image image = await boundary.toImage();
final ByteData? byteData = await image.toByteData(format: ui.ImageByteFormat.png);
final Uint8List pngBytes = byteData!.buffer.asUint8List();
print(pngBytes);
}
@override
Widget build(BuildContext context) {
return RepaintBoundary(
key: globalKey,
child: Center(
child: TextButton(
onPressed: _capturePng,
child: const Text('Hello World', textDirection: TextDirection.ltr),
),
),
);
}
}