Print QR code using esc_pos_printer flutter - flutter

I'm using esc_pos_printer package which can print a receipt over network. I need two features
Save a qr/bar code in the gallery
Print said qr/bar code using the thermal printer/regular printer
For saving the qr code I did:
static Future<File> _saveBarCode(GlobalKey key, String productId) async {
print("save bar code");
RenderRepaintBoundary boundary =
key.currentContext!.findRenderObject() as RenderRepaintBoundary;
ui.Image image = await boundary.toImage();
ByteData? byteData = await image.toByteData(format: ui.ImageByteFormat.png);
Uint8List pngBytes = byteData!.buffer.asUint8List();
final tempPath = (await getTemporaryDirectory()).path;
final path = tempPath + "/" + productId + ".png";
File imgFile = File(path);
print(imgFile.path);
return imgFile.writeAsBytes(pngBytes);
}
and
static void save(GlobalKey key, String productId) async {
_saveBarCode(key, productId).then((value) async {
bool? saved = await GallerySaver.saveImage(value.path);
print("saved: $saved");
}).catchError((error) {
print(error);
});
}
But the printing part is giving me trouble:
void printOverNetwork(GlobalKey key, String productId) async {
const PaperSize paperSize = PaperSize.mm80;
final profile = await CapabilityProfile.load();
final printer = NetworkPrinter(paperSize, profile);
final PosPrintResult result =
await printer.connect('192.168.0.123', port: 9100);
_saveBarCode(key, productId).then((value) {
if (result == PosPrintResult.success) {
// print the qr/barcode
}
});
}
How can I solve the issue?

Related

How can I upload mutiple-photo in flutter app via ImgePicker

I want to add the function which can upload multiple Photo image via ImagePicker
In this code, I can just upload single photo, not mutiple.
This app operating by flutter, dart and firebase server.
[Code]
void dispose() {
textEditingController.dispose();
super.dispose();
}
File _image;
Future _getImage() async {
var image = await ImagePicker.pickImage(
source: ImageSource.gallery,
maxWidth: 1000,
maxHeight: 1000,
);
setState(() {
_image = image;
});
}
Future _uploadFile(BuildContext context) async {
if (_image != null) {
final firebaseStorageRef = FirebaseStorage.instance
.ref()
.child('post')
.child('${DateTime.now().millisecondsSinceEpoch}.png');
final task = firebaseStorageRef.putFile(
_image,
StorageMetadata(contentType: 'image/png'),
);
final storageTaskSnapshot = await task.onComplete;
final downloadUrl = await storageTaskSnapshot.ref.getDownloadURL();
await Firestore.instance.collection('post').add(
{
'contents': textEditingController.text,
'displayName': widget.user.displayName,
'email': widget.user.email,
'photoUrl': downloadUrl,
'userPhotoUrl': widget.user.photoUrl,
});
}
final images = await _picker.pickMultiImage(
maxHeight: 1024,
maxWidth: 1024,
imageQuality: 50,
);
I created here 3 functions used to pick files from imagePicker and to upload them to firebase storage.
first, pick images from gallery:
final imageFiles = await pickImages();
second, upload the images:
final path = 'path/where/you/want/to/save/your/images';
final imageUrls = uploadImages(imagesFiles, path)
print(imageUrls);
you can now use the images urls to save to firestore
Future<List<File>> pickeImages() async {
ImagePicker picker = ImagePicker();
final images = await picker.pickMultiImage(
maxHeight: 1000, maxWidth: 1000, imageQuality: 90);
List<File> files = [];
if (images == null || images.isEmpty) return [];
for (var i = 0; i < images.length; i++) {
final file = File(images[i].path);
files.add(file);
}
return files;
}
Future<String?> _uploadImageFile(File file, String path) async {
try {
final storage = FirebaseStorage.instance;
TaskSnapshot? taskSnapshot;
final storageRef = storage.ref().child(path);
final uploadTask = storageRef.putFile(file);
taskSnapshot = await uploadTask.whenComplete(() {});
final imageUrl = await taskSnapshot.ref.getDownloadURL();
return imageUrl;
} catch (e) {
throw Exception(e.toString());
}
}
Future<List<String>> uploadImages(
List<File> files,
String path,
) async {
final urls = <String>[];
try {
if (files.isNotEmpty) {
for (var i = 0; i < files.length; i++) {
final file = files[i];
final imagePath = '$path/${Random().nextInt(10000)}.jpg';
final url = await _uploadImageFile(file, imagePath);
urls.add(url!);
}
}
return urls;
} on FirebaseException {
rethrow;
}
}
Instead of using ImagePicker.pickImage, use ImagePicker.pickMultiImage. That gives you a List instead of an XFile. Then you can just upload all images in the list. For instance, add an image parameter to your _uploadFile Function so that its function signature is
Future _uploadFile(BuildContext context, XFile image)
and just upload all images like
for (final image of images) {
_uploadFile(context, image)
}

Cannot get the download link after uploading files to firebase storage Flutter

so this is the my file picking and file upload code
class Storage with ChangeNotifier {
PlatformFile? pickedFile;
UploadTask? uploadTask;
Future uploadFile() async {
final path = 'files/${pickedFile!.name}.png';
final file = File(pickedFile!.path!);
final ref = FirebaseStorage.instance.ref().child(path);
ref.putFile(file);
try {
final snapshot = await uploadTask!.whenComplete(() {});
final urlDownload = await snapshot.ref.getDownloadURL();
print(urlDownload);
} catch (e) {
print("this is the error $e " );
}
}
void pickFile() async {
FilePickerResult? result = await FilePicker.platform.pickFiles();
if (result != null) {
File file = File(result.files.single.path!);
pickedFile = result.files.first;
} else {
print("no image picked");
}}}
the code works for upload the image but after that i didnt get any download link, the error is "Null check operator used on a null value" i dont know how to fix it, im still new in this topic, help please
i got the answer, need to change the uploadFile method to this
Future uploadFile() async {
final path = 'files/${pickedFile!.name}.png';
final file = File(pickedFile!.path!);
FirebaseStorage storage = FirebaseStorage.instance;
Reference ref = storage.ref().child(path);
UploadTask uploadTask = ref.putFile(file);
uploadTask.then((res) {
res.ref.getDownloadURL();
});
try {
final snapshot = await uploadTask.whenComplete(() {});
final urlDownload = await snapshot.ref.getDownloadURL();
print(urlDownload);
} catch (e) {
print("this is the error $e " );
}
}

Flutter App for encryption an audio for secure

I have a project with encrypt an audio for secure my data audio and when the user purchase they can play the audio, but until now didn't find how to do that. I found another way by converting the audio data into a string and then encrypting it, I found a code but it's incomplete so I'm still confused about using it.
import 'dart:io';
import 'dart:typed_data';
import 'package:file_picker/file_picker.dart';
import 'package:path_provider/path_provider.dart';
class MediaFile {
Future<String> get docPath async {
Directory appDocDir = await getApplicationDocumentsDirectory();
return appDocDir.path;
}
Future<Uint8List> get audioFileData async {
final String path = await docPath;
final String theFilePath = '$path/test.mp3';
final File theFile = new File(theFilePath);
if (await theFile.exists()) {
return await theFile.readAsBytes();
} else {
File file = await FilePicker.getFile();
return await file.readAsBytes();
}
}
Future<String> dataToString() async {
Uint8List data = await audioFileData;
return new String.fromCharCodes(data);
}
Future<File> saveMediaAsString(String fileName, String fileContent) async {
String path = await docPath;
Directory dataDir = new Directory('$path/data');
if (await dataDir.exists()) {
File file = new File('$path/data/$fileName');
return file.writeAsString(fileContent);
}
await dataDir.create();
File file = new File('$path/data/$fileName');
return file.writeAsString(fileContent);
}
Future<String> readFromStringMediaFile(String fileName) async {
String path = await docPath;
File file = new File('$path/data/$fileName');
return file.readAsString();
}
Uint8List stringToData(dataStr) {
List<int> list = dataStr.codeUnits;
return new Uint8List.fromList(list);
}
Future<File> createAudioFile(String fileName, Uint8List bytes) async {
String path = await docPath;
File file = new File('$path/$fileName');
return await file.writeAsBytes(bytes);
}
//here you can see how to use them
Future<File> testFile() async {
String dataStr = await dataToString();
File savedFile = await saveMediaAsString('codedFile', dataStr);
String contentSavedFile = await readFromStringMediaFile('codedFile');
Uint8List bytes = stringToData(contentSavedFile);
return await createAudioFile('test.mp3', bytes);
}
}

A global key was used multiple time error when using snapshot flutter

[Error Facing][1]
This is the issue I am facing
Please review the code and let me know the error that I am getting thanks
[1]: https://i.stack.imgur.com/HKg7s.jpg
Future<String> saveImage(Uint8List bytes) async {
await [Permission.storage].request();
final time = DateTime.now()
.toIso8601String()
.replaceAll('.', "-")
.replaceAll(':', "-");
final name = "screenshot_$time";
final result = await ImageGallerySaver.saveImage(bytes, name: name);
return result['filePath'];
}
Future saveAndShare(Uint8List bytes) async {
final directory = await getApplicationDocumentsDirectory();
final image = File('${directory.path}/flutter.png');
image.writeAsBytesSync(bytes);
final text = "Save By Lottery App";
await Share.shareFiles([image.path], text: text);
}
}

Flutter image_gallery_saver image not-showing after saving

I want to take a screenshot of my widget. For that, I am using the RepaintBoundary widget and to save the screenshot I use the image_gallery_saver plugin. But after saving the image it is not showing to the gallery. How to solve this issue?
class Utils {
static Future capture(GlobalKey key) async {
DateTime now;
now = DateTime.now();
if (key == null) return null;
final RenderRepaintBoundary boundary =
key.currentContext.findRenderObject();
final image = await boundary.toImage(pixelRatio: 3.0);
final byteData = await image.toByteData(format: ui.ImageByteFormat.png);
final pngByte = byteData.buffer.asUint8List();
// print(pngByte);
if (!(await Permission.storage.status.isGranted)) {
await Permission.storage.request();
}
final result = await ImageGallerySaver.saveImage(
Uint8List.fromList(pngByte),
quality: 90,
name:
'Screeshoot_${now.day.toString()}${now.hour.toString()}${now.minute.toString()}${now.second.toString()}');
return result;
// return pngByte;
}
}
I have done the same in my app but I have used the GallerySaver package instead.
First I have created a method that returns me the path where the image is located and then I use GallerySaver to save the image file.
Future<String> getImagePath() async {
RenderRepaintBoundary boundary = _renderQRandImageWidgetKey.currentContext.findRenderObject();
ui.Image image = await boundary.toImage(pixelRatio: 3.0);
ByteData byteData = await image.toByteData(format: ui.ImageByteFormat.png);
var pngBytes = byteData.buffer.asUint8List();
final tempDirectory = (await getTemporaryDirectory()).path;
final String filePath = '$tempDirectory/MyQRCode.png';
File imgFile = new File('$filePath');
await imgFile.writeAsBytes(pngBytes);
return filePath;
}
_saveImage(String userName) async {
try {
String filePath = await getImagePath();
bool isImageSaved = await GallerySaver.saveImage(filePath, albumName:"AlbumName");
SnackBar _snackbar = SnackBar(
content: isImageSaved ? Text('Image saved in gallery') : Text("There was an error while saving image"),
duration: const Duration(seconds: 1),
);
_scaffoldKey.currentState.showSnackBar(_snackbar);
} catch (exception) {
print("Error $exception");
SnackBar _snackbar = SnackBar(
content: Text('Something went wrong'),
duration: const Duration(seconds: 1),
);
_scaffoldKey.currentState.showSnackBar(_snackbar);
}