首页 > 解决方案 > 从 dart/flutter 在 POS USB 打印机上打印

问题描述

在 Android Flutter 项目中,我需要在 USB POS 打印机上打印,并且为了测试我有一个 Epson TM-T20。发送原始字节将是理想的。flutter_usb_write包不起作用(write返回 false),它的状态有点令人担忧(还没有健全的 null 安全性,主页是克罗地亚语并且没有问题跟踪器)。

还有其他选择吗?

Future<void> printOnPOS(String text) async {
  // text = String.fromCharCodes([27, 64]) + text; // Initialize printer
  text += "\r\n";
  try {
    var flutterUsbWrite = FlutterUsbWrite();
    List<UsbDevice> devices = await flutterUsbWrite.listDevices();
    print("devices: $devices");
    var device = devices[1]; // this picks the printer, checked correct
    var port = await flutterUsbWrite.open(
      vendorId: device.vid,
      productId: device.pid,
    );
    print("port: $port");
    var rw = await flutterUsbWrite.write(Uint8List.fromList(text.codeUnits));
    print("rw: $rw");
    await flutterUsbWrite.close();
  } on PlatformException catch (e) {
    print(e.message);
  }
}

输出:

I/flutter ( 7763): devices: [UsbDevice: e0f-3 VMware Virtual USB Mouse, VMware null, UsbDevice: 4b8-e03 TM-T20, EPSON 405551460005550000]
I/flutter ( 7763): port: UsbDevice: 4b8-e03 TM-T20, EPSON 405551460005550000
I/flutter ( 7763): rw: false
D/UsbDeviceConnectionJNI( 7763): close

标签: androidflutterdart

解决方案


事实证明,一个小小的改变就能flutter_usb_write奏效。

FlutterUsbWritePlugin.java我们的方法中有这个write

      if (this.ep != null && this.mInterface != null && this.m_Connection != null) {
        transferResult = this.m_Connection.bulkTransfer(this.ep, bytes, bytes.length, 0);
      } else {
        if (this.m_Connection.claimInterface(this.mInterface, true)) {
          transferResult = this.m_Connection.bulkTransfer(this.ep, bytes, bytes.length, 0);
        }
      }

表达式中的if计算结果为true,然后调用bulkTransfer失败。

如果我们强制执行该else块,则字节将发送到打印机。

我对文档的理解claimInterface是,在写入设备之前需要此方法。

迁移到健全的 null 安全性的包的一个分支,现在在这里


推荐阅读