Qishu Archives
A shared entry for product documents, interface references, engineering notes, and release-ready delivery records.
Dart SDK
NIB printer SDK integration guide for Flutter and Dart clients.
The Dart SDK is suitable for Flutter applications and for Android, iOS, and desktop clients that want to reuse one set of print templates. When starting, split the code into two layers: the connection layer obtains the device, and the template layer generates ESC, TSPL, or CPCL commands.
Package selection
Section titled “Package selection”| Package | Purpose |
|---|---|
nib |
Standard aggregate package that exports core, Boxliy/Aryten/Lin8inch dialects, and image capabilities. |
nib_core |
ConnectedDevice, WritePipeline, ChunkPolicy, receive sources, and query dispatch. |
nib_esc_boxliy, nib_tspl_boxliy, nib_cpcl_boxliy |
Boxliy dialect builders and response parsers. |
nib_esc, nib_tspl, nib_cpcl |
Aryten-compatible dialects. |
nib_esc_lin8inch, nib_tspl_lin8inch |
Lin8inch dialects. |
nib_bluetooth_ble |
BLE scanning, connection, characteristic selection, and credit flow control. |
nib_bluetooth_classic |
Classic Bluetooth printer connection. |
Production projects usually start with package:nib/nib.dart. Use lower-level packages directly only when modules need to be delivered separately.
ConnectedDevice contract
Section titled “ConnectedDevice contract”After connecting a real printer, wrap it as ConnectedDevice<T>:
abstract class ConnectedDevice<T> { T origin(); String? deviceName(); String? deviceMac(); ConnectionState connectionState(); Stream<ConnectionState> connectionStateChanges(); Future<void> disconnect(); Future<void> write(Uint8List data, {bool sendDone = true}); Stream<Uint8List> read(ReadOptions? options);}BLE, classic Bluetooth, and test devices can all use the same builders and write pipeline as long as they implement this contract.
First print
Section titled “First print”The following example uses the Aryten TSPL builder from the standard package. NullDevice is only for local testing. In real projects, replace it with a device returned by a BLE or classic Bluetooth connection.
import 'package:nib/nib.dart';
final device = NullDevice.instance;
final printer = TsplAryten(device) ..size(40, 30) ..cls() ..text(x: 20, y: 20, content: 'NIB SDK') ..print();
await printer.flush();flush() writes the current builder bytes to the device it is bound to. For finer progress, timeout, or chunk control, use WritePipeline directly:
final result = await WritePipeline.write( device, printer.bytes(), options: WriteOptions( chunkPolicy: ChunkPolicy.fixed(1024), ),);
if (!result.success) { // 根据 cancelled、timedOut、backpressured 做业务处理。}The core default chunk size is 1024 bytes, meaning WriteOptions() uses ChunkPolicy.fixed(NibDefaults.chunkSize) by default.
BLE chunking and credit
Section titled “BLE chunking and credit”Normal BLE writes usually need chunking based on MTU:
final flow = BleFlowController.forNegotiatedMtu(185);
await WritePipeline.write( device, printer.bytes(), options: flow.writeOptions,);nib_bluetooth_ble also provides credit flow control:
| API | Purpose |
|---|---|
BleCreditOptions |
Enables credit and configures UUIDs, strategy, initial credit, MTU, and fallback. |
BleLaneCreditFlowControlStrategy |
lane-credit strategy, with default initial credit 1. |
BleSignalCreditFlowControlStrategy |
signal-credit strategy, with default initial credit 0. |
selectBleCreditCharacteristicPair() |
Finds the service, write, read, and credit characteristic combination. |
Default UUIDs are FF00 service, FF02 write, FF01 read, and FF03 credit. The default initial MTU is 20. lane-credit defaults to payload overhead 3, and signal-credit defaults to payload overhead 0. BleCreditOptions.enabled defaults to false; enable it only when the device requires credit notifications.
Receiving, querying, and parsing
Section titled “Receiving, querying, and parsing”Core receive and query types include ReceiveSource, StreamReceiveSource, ReceiveSources.fromDevice(), QueryDispatcher<T>, and PendingQuery<T>. ConnectedDevice also has a receiveSource() extension method that wraps the read() stream as a receive source.
Boxliy dialects provide these parsers:
| Dialect | Parser |
|---|---|
| ESC | EscResponseParser |
| TSPL | TsplResponseParser |
| CPCL | CpclResponseParser |
EscResponseParser and TsplResponseParser commonly use parse(query, data). CPCL supports both query parsing and parseEvent(...) for status frames.
Methods and Commands
The tables below list the public entry points integration teams usually need. Builder methods generate printer commands; actual availability still depends on the ESC, TSPL, CPCL, or Lin8inch command family supported by the target firmware.
Core, Connection, and Writing
| Object | Method / Command | Purpose | Parameters |
|---|---|---|---|
ConnectedDevice<T> | origin(), deviceName(), deviceMac(), connectionState(), connectionStateChanges(), disconnect(), write(data), read(options) | Abstracts the real printer connection for templates, write pipelines, and query handling. | `data` is the byte payload; `sendDone` lets adapters signal completion; `ReadOptions` controls read behavior. |
WritePipeline | write(device, data, options) | Writes built bytes to a device with chunking, timeout, cancellation, and flow-control rules. | `device` is the connection; `data` is the bytes; `WriteOptions` contains `ChunkPolicy`, `WriteMode`, cancellation, timeout, and backpressure. |
ReceiveSource / QueryDispatcher | start(listener), stop(), query(matcher, timeout), cancel(), shutdown() | Routes device responses into listeners or query dispatchers for status, battery, model, and similar queries. | `matcher` maps raw responses to results; `timeout` bounds waiting; listeners receive data/error/closed events. |
BLE credit | BleCreditOptions, BleLaneCreditFlowControlStrategy, BleSignalCreditFlowControlStrategy, selectBleCreditCharacteristicPair() | Handles BLE characteristic selection, MTU chunking, credit notifications, and fallback writes. | Configure service/write/read/credit UUIDs, initialCredit, initialMtu, payload overhead, strategy, and fallbackMode. |
Command Builders
| Object | Method / Command | Purpose | Parameters |
|---|---|---|---|
EscBoxliy / EscAryten | reset(), raw(), newLine(), feed(), lineRow(), lineDot(), backLineDot(), location(), cut(), lineDotCut(), enable(), stopJob(), wakeup(), batteryVolume(), info(), model(), version(), printerVersion(), name(), mac(), sn(), state(), status(), barcode(), qrcode(), image(), imageGray(), clear(), flush() | Builds ESC/Boxliy commands for receipt, portable, and ESC-compatible printers. | Use `raw` for text or bytes; rows/dots/location control feed and positioning; barcode/QR use value/type/height/size/level; images use bitmap, byteWidth, height, or a prepared bitmap. |
TsplBoxliy / TsplAryten | size(), gap(), bline(), continuous(), label(), direction(), codePage(), speed(), density(), reference(), offset(), shift(), gapSensor(), ribbon(), cut(), tear(), peel(), cls(), text(), barcode(), qrcode(), dmatrix(), line(), box(), circle(), ellipse(), image(), print(), raw(), clear(), flush() | Builds TSPL label commands for templates with paper size, coordinates, barcodes, and QR codes. | `size/gap` use millimeters; drawing primitives use x/y/width/height/thickness; text uses font/rotation/xMul/yMul/content; images use bitmap or prepared bitmap. |
CpclBoxliy / CpclAryten | begin(), pageWidth(), feed(), gapSense(), barSense(), paperType(), text(), barcode(), qrcode(), line(), box(), bold(), underline(), waterMark(), inverseLine(), image(), form(), print(), status(), realtimeStatus(), sn(), model(), version(), batteryVolume(), raw(), clear(), flush() | Builds CPCL label commands for page setup, text, lines, barcodes, and images. | `begin` takes height/copies; text uses font/size/x/y/content/rotation; barcodes use type/width/ratio/height/x/y/value; images use x/y/bitmap/byteWidth/height. |
EscLin8inch | batteryLevel(), extendedModel(), bootVersion(), advancedDensity(), advancedDensityStatus(), mediaProfile(), mediaProfileStatus(), grayMode(), wirelessProvisioning(), wirelessProvisioningStatus(), compressedRasterTransport(), mediaTag(), mediaTagUid(), consumedMediaLength(), remainingMediaLength(), restoreLabelStartPosition(), alternateMotionProfile() | Adds Lin8inch telemetry, media, provisioning, and raster transport commands on top of ESC. | `advancedDensity` takes a density level; `mediaProfile` takes a media enum; `wirelessProvisioning` takes ssid/password/mode. |
TsplLin8inch | automaticStatusFeedback(), printCompletion(), printerStatus(), firmwareVersion(), serialNumber(), macAddress(), deviceSpeed(), deviceSelfTest(), thermalStatus(), productId(), versionInfo(), selfTestPage(), modelSetting(), serialSetting(), versionSetting(), gbkCodepage(), utf8Codepage(), gapDetection(), configureStock(), configurePresentation(), twoColorRibbon(), directThermal() | Adds Lin8inch status feedback, media, ribbon, and presentation commands on top of TSPL. | `printCompletion` takes a 4-byte token; `printerStatus` takes a status flag; `configureStock` takes sensor, markOrGapMm, and offsetMm. |
Response Parsing
| Object | Method / Command | Purpose | Parameters |
|---|---|---|---|
EscResponseParser / TsplResponseParser / CpclResponseParser | parse(query, data), parse(data) | Parses printer responses into status, battery, text, MAC, event, or unknown response objects. | `query` identifies status, battery, version, model, serial-number, and similar queries; `data` is the raw response. |
Practical recommendations
Section titled “Practical recommendations”- Confirm ESC, TSPL, or CPCL by printer model before mixing dialects in a template.
- Keep connection, permissions, and reconnect logic in the service layer. Print templates should only care about paper width, coordinates, and content.
- For label printing, confirm millimeter size, DPI, gap, and density before writing templates.
- Real BLE hardware tests should cover large images, continuous printing, reconnects, and credit notifications.