Flutter USB热敏打印机控制插件flutter_usb_thermal_plugin的使用

Flutter USB热敏打印机控制插件flutter_usb_thermal_plugin的使用

获取插件

首先,在你的pubspec.yaml文件中添加插件依赖:

dependencies:
  flutter_usb_thermal_plugin: ^版本号

然后运行以下命令安装插件:

flutter pub add flutter_usb_thermal_plugin

使用示例

以下是完整的示例代码,展示了如何使用flutter_usb_thermal_plugin来连接并打印数据到USB热敏打印机。

example/lib/main.dart

import 'package:flutter_usb_thermal_plugin/flutter_usb_thermal_plugin.dart';

import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_usb_thermal_plugin/model/usb_device_model.dart';

void main() => runApp(const MyApp());

class MyApp extends StatefulWidget {
  const MyApp({super.key});

  @override
  State<MyApp> createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
  List<UsbDevice> devices = [];
  FlutterUsbThermalPlugin flutterUsbPrinter = FlutterUsbThermalPlugin();
  bool connected = false;

  @override
  initState() {
    super.initState();
    _getDevicelist();
  }

  _getDevicelist() async {
    List<UsbDevice> results = [];
    results = await flutterUsbPrinter.getUSBDeviceList();

    debugPrint("设备数量: ${results.length}");
    setState(() {
      devices = results;
    });
  }

  _connect(int vendorId, int productId) async {
    bool? returned = false;
    try {
      returned = await flutterUsbPrinter.connect(vendorId, productId);
    } on PlatformException {
      // response = 'Failed to get platform version.';
    }
    if (returned!) {
      setState(() {
        connected = true;
      });
    }
  }

  _print() async {
    try {
      var data = Uint8List.fromList(utf8.encode("Hello world Testing ESC POS printer..."));
      await flutterUsbPrinter.write(data);
      // await FlutterUsbPrinter.printRawData("text");
      // await FlutterUsbPrinter.printText("Testing ESC POS printer...");
    } on PlatformException {
      // response = 'Failed to get platform version.';
    }
  }

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: const Text('USB 打印机'),
          actions: <Widget>[
            IconButton(
                icon: const Icon(Icons.refresh),
                onPressed: () => _getDevicelist()),
            connected == true
                ? IconButton(
                    icon: const Icon(Icons.print),
                    onPressed: () {
                      _print();
                    })
                : Container(),
          ],
        ),
        body: devices.isNotEmpty
            ? ListView(
                scrollDirection: Axis.vertical,
                children: _buildList(devices),
              )
            : null,
      ),
    );
  }

  List<Widget> _buildList(List<UsbDevice> devices) {
    return devices
        .map((device) => ListTile(
              onTap: () {
                _connect(int.parse(device.vendorId), int.parse(device.productId));
              },
              leading: const Icon(Icons.usb),
              title: Text('${device.manufacturer} ${device.productName}'),
              subtitle: Text('${device.vendorId} ${device.productId}'),
            ))
        .toList();
  }
}

代码解释

  1. 初始化插件

    FlutterUsbThermalPlugin flutterUsbPrinter = FlutterUsbThermalPlugin();
    
  2. 获取设备列表

    _getDevicelist() async {
      List<UsbDevice> results = [];
      results = await flutterUsbPrinter.getUSBDeviceList();
    
      debugPrint("设备数量: ${results.length}");
      setState(() {
        devices = results;
      });
    }
    
  3. 连接打印机

    _connect(int vendorId, int productId) async {
      bool? returned = false;
      try {
        returned = await flutterUsbPrinter.connect(vendorId, productId);
      } on PlatformException {
        // response = 'Failed to get platform version.';
      }
      if (returned!) {
        setState(() {
          connected = true;
        });
      }
    }
    
  4. 打印数据

    _print() async {
      try {
        var data = Uint8List.fromList(utf8.encode("Hello world Testing ESC POS printer..."));
        await flutterUsbPrinter.write(data);
        // await FlutterUsbPrinter.printRawData("text");
        // await FlutterUsbPrinter.printText("Testing ESC POS printer...");
      } on PlatformException {
        // response = 'Failed to get platform version.';
      }
    }
    
  5. 构建设备列表

    List<Widget> _buildList(List<UsbDevice> devices) {
      return devices
          .map((device) => ListTile(
                onTap: () {
                  _connect(int.parse(device.vendorId), int.parse(device.productId));
                },
                leading: const Icon(Icons.usb),
                title: Text('${device.manufacturer} ${device.productName}'),
                subtitle: Text('${device.vendorId} ${device.productId}'),
              ))
          .toList();
    }
    

更多关于Flutter USB热敏打印机控制插件flutter_usb_thermal_plugin的使用的实战教程也可以访问 https://www.itying.com/category-92-b0.html

1 回复

更多关于Flutter USB热敏打印机控制插件flutter_usb_thermal_plugin的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html


flutter_usb_thermal_plugin 是一个用于在 Flutter 应用中控制 USB 热敏打印机的插件。它允许你通过 USB 连接发送打印指令到热敏打印机,从而实现打印功能。

安装插件

首先,你需要在 pubspec.yaml 文件中添加 flutter_usb_thermal_plugin 插件的依赖:

dependencies:
  flutter:
    sdk: flutter
  flutter_usb_thermal_plugin: ^latest_version

然后运行 flutter pub get 来安装插件。

基本使用

1. 获取 USB 设备列表

你可以使用 flutter_usb_thermal_plugin 来获取当前连接的 USB 设备列表:

import 'package:flutter_usb_thermal_plugin/flutter_usb_thermal_plugin.dart';

Future<void> getUsbDevices() async {
  List<UsbDevice> devices = await FlutterUsbThermalPlugin.getUsbDevices();
  for (var device in devices) {
    print('Device: ${device.deviceName}, Vendor ID: ${device.vendorId}, Product ID: ${device.productId}');
  }
}

2. 连接打印机

在获取到设备列表后,你可以选择其中一个设备进行连接:

Future<void> connectToPrinter() async {
  List<UsbDevice> devices = await FlutterUsbThermalPlugin.getUsbDevices();
  if (devices.isNotEmpty) {
    UsbDevice printer = devices.first;
    bool isConnected = await FlutterUsbThermalPlugin.connect(printer);
    if (isConnected) {
      print('Connected to printer: ${printer.deviceName}');
    } else {
      print('Failed to connect to printer');
    }
  }
}

3. 发送打印指令

连接成功后,你可以发送打印指令到打印机。通常,热敏打印机使用 ESC/POS 指令集进行控制。你可以使用 flutter_usb_thermal_plugin 提供的 printText 方法来发送文本:

Future<void> printText() async {
  String text = "Hello, World!";
  bool isPrinted = await FlutterUsbThermalPlugin.printText(text);
  if (isPrinted) {
    print('Text printed successfully');
  } else {
    print('Failed to print text');
  }
}

4. 断开连接

打印完成后,记得断开与打印机的连接:

Future<void> disconnectPrinter() async {
  bool isDisconnected = await FlutterUsbThermalPlugin.disconnect();
  if (isDisconnected) {
    print('Disconnected from printer');
  } else {
    print('Failed to disconnect from printer');
  }
}

高级功能

除了基本的文本打印,flutter_usb_thermal_plugin 还支持其他 ESC/POS 指令,例如打印条形码、二维码、图片等。你可以参考插件的文档或源代码来了解更多高级功能。

注意事项

  1. 权限:在 Android 上,使用 USB 设备需要获取相应的权限。你需要确保在 AndroidManifest.xml 中添加 USB 权限声明:

    <uses-permission android:name="android.permission.USB_PERMISSION" />
    
  2. 设备兼容性:不同的热敏打印机可能支持不同的指令集,因此在开发时需要确保你的打印指令与目标打印机兼容。

  3. USB 连接:确保在连接打印机时,设备已通过 USB 正确连接,并且在 Android 设备上已授权访问 USB 设备。

示例代码

以下是一个完整的示例代码,展示了如何使用 flutter_usb_thermal_plugin 连接打印机并打印文本:

import 'package:flutter/material.dart';
import 'package:flutter_usb_thermal_plugin/flutter_usb_thermal_plugin.dart';

void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  [@override](/user/override)
  Widget build(BuildContext context) {
    return MaterialApp(
      home: PrinterScreen(),
    );
  }
}

class PrinterScreen extends StatefulWidget {
  [@override](/user/override)
  _PrinterScreenState createState() => _PrinterScreenState();
}

class _PrinterScreenState extends State<PrinterScreen> {
  [@override](/user/override)
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('USB Thermal Printer Example'),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            ElevatedButton(
              onPressed: getUsbDevices,
              child: Text('Get USB Devices'),
            ),
            ElevatedButton(
              onPressed: connectToPrinter,
              child: Text('Connect to Printer'),
            ),
            ElevatedButton(
              onPressed: printText,
              child: Text('Print Text'),
            ),
            ElevatedButton(
              onPressed: disconnectPrinter,
              child: Text('Disconnect Printer'),
            ),
          ],
        ),
      ),
    );
  }

  Future<void> getUsbDevices() async {
    List<UsbDevice> devices = await FlutterUsbThermalPlugin.getUsbDevices();
    for (var device in devices) {
      print('Device: ${device.deviceName}, Vendor ID: ${device.vendorId}, Product ID: ${device.productId}');
    }
  }

  Future<void> connectToPrinter() async {
    List<UsbDevice> devices = await FlutterUsbThermalPlugin.getUsbDevices();
    if (devices.isNotEmpty) {
      UsbDevice printer = devices.first;
      bool isConnected = await FlutterUsbThermalPlugin.connect(printer);
      if (isConnected) {
        print('Connected to printer: ${printer.deviceName}');
      } else {
        print('Failed to connect to printer');
      }
    }
  }

  Future<void> printText() async {
    String text = "Hello, World!";
    bool isPrinted = await FlutterUsbThermalPlugin.printText(text);
    if (isPrinted) {
      print('Text printed successfully');
    } else {
      print('Failed to print text');
    }
  }

  Future<void> disconnectPrinter() async {
    bool isDisconnected = await FlutterUsbThermalPlugin.disconnect();
    if (isDisconnected) {
      print('Disconnected from printer');
    } else {
      print('Failed to disconnect from printer');
    }
  }
}
回到顶部