Last active
July 22, 2023 16:11
-
-
Save leadpresence/c6fedb74490caa2435d63e60ac9d531f to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| import 'dart:io'; | |
| import 'dart:ui' as ui; | |
| import 'package:flutter/foundation.dart'; | |
| import 'package:flutter/material.dart'; | |
| import 'package:flutter/rendering.dart'; | |
| import 'package:flutter/services.dart'; | |
| import 'package:logger/logger.dart'; | |
| import 'package:path_provider/path_provider.dart'; | |
| import 'package:permission_handler/permission_handler.dart'; | |
| class ExampleWidget extends StatelessWidget { | |
| const ExampleWidget({super.key}); | |
| GlobalKey _globalKey = GlobalKey(); | |
| File? qrFilePath; | |
| @override | |
| Widget build(BuildContext context) { | |
| return Scaffold( | |
| body:Center(child: | |
| GesturDetector( | |
| ontap:(){ | |
| saveImageAsJPEG(); | |
| }, | |
| child:Text("TapMe); | |
| ); | |
| } | |
| } | |
| Future<ui.Image> captureImage() async { | |
| RenderRepaintBoundary boundary = _globalKey.currentContext!.findRenderObject() as RenderRepaintBoundary; | |
| final image = await boundary.toImage(pixelRatio: 1.0); | |
| return image; | |
| } | |
| Future<void> saveImageAsJPEG() async { | |
| final permissionStatus = await Permission.storage.status; | |
| if (permissionStatus.isGranted) { | |
| final appDocDirectory = Platform.isAndroid ? await getTemporaryDirectory() | |
| : await getApplicationSupportDirectory(); | |
| qrFilePath = File(appDocDirectory.path + '/qr_${firstName}.png'); | |
| if(mounted){ | |
| ui.Image image = await captureImage(); | |
| ByteData? byteData = await image.toByteData(format: ui.ImageByteFormat.png); | |
| if (byteData != null) { | |
| final buffer = byteData.buffer.asUint8List(); | |
| await qrFilePath?.writeAsBytes(buffer); | |
| } else { | |
| logger.d('Image bytes is Null or Empty'); | |
| } | |
| } | |
| } else { | |
| /// Permission not present | |
| /// request permission | |
| if (permissionStatus.isDenied) { | |
| await Permission.storage.request(); | |
| } else if (permissionStatus.isPermanentlyDenied) { | |
| await openAppSettings(); | |
| } | |
| } | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment