Capture Widgets as Images with Flutter: widgets_to_image
Published on by Flutter News Hub
The flutter widgets_to_image package empowers you to effortlessly convert any widget you design into a high-quality image. This capability opens up endless possibilities for sharing and preserving your widget creations.
Installation
- Add the following to your
pubspec.yaml
file:
dependencies:
widgets_to_image: any
-
Run
pub get
to fetch the package. -
Import the package in your Flutter project:
import 'package:widgets_to_image/widgets_to_image.dart';
Usage
1. Initialize WidgetsToImageController
WidgetsToImageController controller = WidgetsToImageController();
2. Wrap your widget with WidgetsToImage
Widget myWidget = Card(
child: Text('Hello, world!'),
);
Widget wrappedWidget = WidgetsToImage(
controller: controller,
child: myWidget,
);
3. Capture the image as bytes
Uint8List? bytes = await controller.capture();
Sample Code:
import 'package:flutter/material.dart';
import 'package:widgets_to_image/widgets_to_image.dart';
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
WidgetsToImageController controller = WidgetsToImageController();
return MaterialApp(
home: Scaffold(
body: Center(
child: WidgetsToImage(
controller: controller,
child: Card(
child: Text('Hello, world!'),
),
),
),
floatingActionButton: FloatingActionButton(
onPressed: () async {
Uint8List? bytes = await controller.capture();
// Do something with the bytes...
},
child: Icon(Icons.save),
),
),
);
}
}
Screenshots
Image of WidgetsToImage in action
Credits
Inspiration and technical guidance from Parth Jansari: