PrintUsb Class

PrintUsb is a utility class designed to manage USB printing in a Flutter application using platform-specific method channels. It provides functions to list USB devices, connect to a printer, send data for printing, and close connections.

Features

  • Retrieve a list of available USB devices.
  • Connect to a specific USB printer.
  • Print data (bytes) to a USB printer.
  • Close the connection with the printer.

Methods

Method Name Description
getList Retrieves a list of available USB devices and filters those that are available for printing.
connect Connects to a USB printer by its name. Returns true if the connection is successful, otherwise false.
_close Closes the connection to the currently connected USB printer. Returns true if successful, otherwise false.
printBytes Sends a list of bytes to the connected USB printer for printing. Returns true if printing succeeds, otherwise false.

Creating Print Data

You can generate the bytes needed for printing using the flutter_esc_pos_utils package. This package provides utilities to format and generate ESC/POS commands for printers.

Usage Example

import 'package:your_project/print_usb.dart';
import 'package:your_project/model/usb_device.dart';

void main() async {
  List<UsbDevice> devices = await PrintUsb.getList();

  if (devices.isNotEmpty) {
    bool connected = await PrintUsb.connect(name: devices[0].name);

    if (connected) {
      List<int> data = [0x48, 0x65, 0x6C, 0x6C, 0x6F]; // Example data: "Hello"
      bool success = await PrintUsb.printBytes(bytes: data, device: devices[0]);

      if (success) {
        print("Print successful!");
      } else {
        print("Print failed.");
      }
    }
  }
}