-
Notifications
You must be signed in to change notification settings - Fork 347
Open
Description
Overview
Solution for save QR Code file on Flutter Web
Screen.Recording.2025-06-07.at.13.47.37.mov
Approach
Use screenshot to capture QrImageView and use universal_html to save image file
Example
- capture
QrImageView
final ScreenshotController _screenshotController = ScreenshotController();
Screenshot(
controller: _screenshotController,
child: QrImageView(
data: _textController.text.trim(),
version: QrVersions.auto,
size: _qrSize,
gapless: true,
backgroundColor: _qrBackgroundColor,
eyeStyle: QrEyeStyle(
eyeShape: QrEyeShape.square,
color: _qrColor,
),
dataModuleStyle: QrDataModuleStyle(
dataModuleShape: QrDataModuleShape.square,
color: _qrColor,
),
),
)- Capture and save file
void _saveQRCode() {
_screenshotController.capture().then((result) {
if (result == null) return;
final fileName = 'qr_${DateTime.now()}.png';
downloadImage(result, fileName);
});
}
// import 'package:universal_html/html.dart' as html;
// import 'dart:typed_data';
void downloadImage(Uint8List imageBytes, String fileName) {
// Determine the MIME type based on the file extension
String mimeType;
if (fileName.toLowerCase().endsWith('.png')) {
mimeType = 'image/png';
} else if (fileName.toLowerCase().endsWith('.jpg') ||
fileName.toLowerCase().endsWith('.jpeg')) {
mimeType = 'image/jpeg';
} else if (fileName.toLowerCase().endsWith('.gif')) {
mimeType = 'image/gif';
} else {
mimeType = 'application/octet-stream'; // Default for unknown types
}
// Create a Blob from the Uint8List
final html.Blob blob = html.Blob([imageBytes], mimeType);
// Create an object URL from the Blob
final String url = html.Url.createObjectUrlFromBlob(blob);
// Create a dummy anchor element
final html.AnchorElement anchor =
html.document.createElement('a') as html.AnchorElement
..href = url
..style.display =
'none' // Hide the element
..download = fileName; // Set the download filename
// Add the anchor to the document body and click it
html.document.body?.children.add(anchor);
anchor.click();
// Clean up: remove the anchor and revoke the URL
html.document.body?.children.remove(anchor);
html.Url.revokeObjectUrl(url);
}
Metadata
Metadata
Assignees
Labels
No labels