printData method
Implementation
Future<void> printData(
Printer printer,
List<int> bytes, {
bool longData = false,
}) async {
if (printer.connectionType == ConnectionType.USB) {
try {
await FlutterThermalPrinterPlatform.instance.printText(
printer,
Uint8List.fromList(bytes),
path: printer.address,
);
} catch (e) {
log("FlutterThermalPrinter: Unable to Print Data $e");
}
} else {
try {
final device = BluetoothDevice.fromId(printer.address!);
if (!device.isConnected) {
log('Device is not connected');
return;
}
final services = (await device.discoverServices()).skipWhile((value) =>
value.characteristics
.where((element) => element.properties.write)
.isEmpty);
BluetoothCharacteristic? writecharacteristic;
for (var service in services) {
for (var characteristic in service.characteristics) {
if (characteristic.properties.write) {
writecharacteristic = characteristic;
break;
}
}
}
if (writecharacteristic == null) {
log('No write characteristic found');
return;
}
if (longData) {
int mtu = (await device.mtu.first) - 30;
final numberOfTimes = bytes.length / mtu;
final numberOfTimesInt = numberOfTimes.toInt();
int timestoPrint = 0;
if (numberOfTimes > numberOfTimesInt) {
timestoPrint = numberOfTimesInt + 1;
} else {
timestoPrint = numberOfTimesInt;
}
for (var i = 0; i < timestoPrint; i++) {
final data = bytes.sublist(
i * mtu,
((i + 1) * mtu) > bytes.length
? bytes.length
: ((i + 1) * mtu));
await writecharacteristic.write(data);
}
} else {
await writecharacteristic.write(bytes);
}
return;
} catch (e) {
log('Failed to print data to device $e');
}
}
}