How to convert barcode to image in Flutter SfBarcodeGenarator
In this article, we will explain how to convert a barcode to image in SfBarcodeGenarator using RepaintBoundary.
Generating barcodes is a common feature in mobile applications, but converting them into images can be useful when you need to save the barcode for offline use or display it outside of the barcode widget. The RepaintBoundary widget in Flutter provides an easy way to capture any widget as an image, and by combining it with SfBarcodeGenarator, we can create, capture, and display a barcode as an image within the app.
The following steps will explain how to capture and convert the barcode into an image using Flutter’s RenderRepaintBoundary and display it on a new screen.
Step 1: Create a GlobalKey for RepaintBoundary, which is used to uniquely identify the widget that needs to be captured as an image.
final GlobalKey _globalKey = GlobalKey();
Step 2: Place the SfBarcodeGenarator inside a RepaintBoundary, allowing it to be rendered as an image.
@override
Widget build(BuildContext context) {
Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
SizedBox(
child: RepaintBoundary(
key: _globalKey,
child: SfBarcodeGenerator(value: 'http://www.syncfusion.com'),
),
),
ElevatedButton(
onPressed: _renderBarcodeImage,
child: const Text('Barcode to image'),
),
],
);
}
Step 3: Create a function to capture the barcode as an image, using RenderRepaintBoundary to convert the widget’s content into the specified format, such as PNG.
Future<void> _renderBarcodeImage() async {
final RenderRepaintBoundary boundary = _globalKey.currentContext?.findRenderObject() as RenderRepaintBoundary;
final ui.Image data = await boundary.toImage(pixelRatio: 3.0);
final bytes = await data.toByteData(format: ui.ImageByteFormat.png);
await Navigator.of(context).push(
MaterialPageRoute(
builder: (BuildContext context) {
return Scaffold(
body: Center(
child: Container(
color: Colors.white,
child: Image.memory(bytes!.buffer.asUint8List()),
),
),
);
},
),
);
}
Now, convert the barcode to an image in Flutter using the SfBarcodeGenarator have been implemented as shown below.
Conclusion
I hope you enjoyed learning about how to convert barcode to image in Flutter SfBarcodeGenarator.
You can refer to our Flutter BarcodeGenarator feature tour page to know about its other groundbreaking feature representations. You can also explore our Flutter BarcodeGenarator documentation to understand how to create and manipulate data.
For current customers, you can check out our components from the License and Downloads page. If you are new to Syncfusion, you can try our 30-day free trial to check out our other controls.
If you have any queries or require clarifications, please let us know in the comments section below. You can also contact us through our
support forums, Direct-Trac, or feedback portal. We are always happy to assist you!