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;
}
const maxChunkSize = 512;
for (var i = 0; i < bytes.length; i += maxChunkSize) {
final chunk = bytes.sublist(
i,
i + maxChunkSize > bytes.length ? bytes.length : i + maxChunkSize,
);
await writeCharacteristic.write(
Uint8List.fromList(chunk),
withoutResponse: true,
);
}
return;
} catch (e) {
log('Failed to print data to device $e');
}
}
}