writeBytes method
writeBytes writes raw data to the network socket in chunks.
Data is sent in chunkSize-byte pieces with a small delay and flush
between each chunk. This prevents the printer's internal buffer from
overflowing, which can cause:
- Incomplete prints / missing lines
- Printer treating data as multiple "pages" (A4-height output)
- Garbled output from buffer wrap-around
chunkSize — max bytes per write (default: 4096).
chunkDelayMs — delay in ms between chunks (default: 5).
Implementation
@override
Future writeBytes(
List<int> data, {
int chunkSize = defaultChunkSize,
int chunkDelayMs = defaultChunkDelayMs,
}) async {
if (socket == null) {
return Future.error(
'Socket is not connected. Call connect() before writeBytes().');
}
try {
final bytes = Uint8List.fromList(data);
final totalLength = bytes.length;
if (totalLength <= chunkSize) {
// Small payload — send in one go.
socket!.add(bytes);
await socket!.flush();
} else {
// Large payload — send in chunks with flush + delay.
int offset = 0;
while (offset < totalLength) {
final end =
(offset + chunkSize > totalLength) ? totalLength : offset + chunkSize;
socket!.add(bytes.sublist(offset, end));
await socket!.flush();
offset = end;
// Small delay to let the printer process the chunk.
if (offset < totalLength && chunkDelayMs > 0) {
await Future.delayed(Duration(milliseconds: chunkDelayMs));
}
}
}
} catch (e) {
return Future.error('Failed to write bytes: $e');
}
}