Flutter蓝牙打印机插件drago_blue_printer的使用

发布于 1周前 作者 caililin 来自 Flutter

Flutter蓝牙打印机插件drago_blue_printer的使用

简介

drago_blue_printer 是一个用于通过蓝牙连接热敏打印机的新 Flutter 插件(仅支持 Android)。此插件仍在开发中。注意:请将您的项目迁移到 AndroidX。

开始使用

1. 添加依赖

在您的 pubspec.yaml 文件中添加以下依赖:

dependencies:
  drago_blue_printer: ^any

2. 安装依赖

您可以从命令行安装依赖:

$ flutter packages get

或者,您的编辑器可能支持 flutter packages get。请查阅您的编辑器文档以获取更多信息。

3. 导入插件

现在在您的 Dart 代码中可以使用:

import 'package:drago_blue_printer/drago_blue_printer.dart';

示例代码

以下是一个完整的示例代码,展示了如何使用 drago_blue_printer 插件连接和打印内容。

主应用代码

import 'dart:io';
import 'dart:typed_data';
import 'package:flutter/material.dart';
import 'dart:async';
import 'package:drago_blue_printer/drago_blue_printer.dart';
import 'package:flutter/services.dart';
import 'package:path_provider/path_provider.dart';

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

class MyApp extends StatefulWidget {
  @override
  _MyAppState createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
  DragoBluePrinter bluetooth = DragoBluePrinter.instance;

  List<BluetoothDevice> _devices = [];
  BluetoothDevice? _device;
  bool _connected = false;
  String? pathImage;

  @override
  void initState() {
    super.initState();
    initPlatformState();
    initSavetoPath();
  }

  initSavetoPath() async {
    final filename = 'yourlogo.png';
    var bytes = await rootBundle.load("assets/images/yourlogo.png");
    String dir = (await getApplicationDocumentsDirectory()).path;
    writeToFile(bytes, '$dir/$filename');
    setState(() {
      pathImage = '$dir/$filename';
    });
  }

  Future<void> initPlatformState() async {
    bool isConnected = await bluetooth.isConnected ?? false;
    List<BluetoothDevice> devices = [];

    try {
      devices = await bluetooth.getBondedDevices();
    } on PlatformException {
      // TODO - Error
    }

    bluetooth.onStateChanged().listen((state) {
      switch (state) {
        case DragoBluePrinter.CONNECTED:
          setState(() {
            _connected = true;
            print("bluetooth device state: connected");
          });
          break;
        case DragoBluePrinter.DISCONNECTED:
          setState(() {
            _connected = false;
            print("bluetooth device state: disconnected");
          });
          break;
        case DragoBluePrinter.DISCONNECT_REQUESTED:
          setState(() {
            _connected = false;
            print("bluetooth device state: disconnect requested");
          });
          break;
        case DragoBluePrinter.STATE_TURNING_OFF:
          setState(() {
            _connected = false;
            print("bluetooth device state: bluetooth turning off");
          });
          break;
        case DragoBluePrinter.STATE_OFF:
          setState(() {
            _connected = false;
            print("bluetooth device state: bluetooth off");
          });
          break;
        case DragoBluePrinter.STATE_ON:
          setState(() {
            _connected = false;
            print("bluetooth device state: bluetooth on");
          });
          break;
        case DragoBluePrinter.STATE_TURNING_ON:
          setState(() {
            _connected = false;
            print("bluetooth device state: bluetooth turning on");
          });
          break;
        case DragoBluePrinter.ERROR:
          setState(() {
            _connected = false;
            print("bluetooth device state: error");
          });
          break;
        default:
          print(state);
          break;
      }
    });

    if (!mounted) return;
    setState(() {
      _devices = devices;
    });

    if (isConnected) {
      setState(() {
        _connected = true;
      });
    }
  }

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: Text('Blue Thermal Printer'),
        ),
        body: Container(
          child: Padding(
            padding: const EdgeInsets.all(8.0),
            child: ListView(
              children: <Widget>[
                Row(
                  crossAxisAlignment: CrossAxisAlignment.center,
                  mainAxisAlignment: MainAxisAlignment.start,
                  children: <Widget>[
                    SizedBox(width: 10),
                    Text(
                      'Device:',
                      style: TextStyle(fontWeight: FontWeight.bold),
                    ),
                    SizedBox(width: 30),
                    Expanded(
                      child: DropdownButton(
                        items: _getDeviceItems(),
                        onChanged: (value) => setState(() => _device = value),
                        value: _device,
                      ),
                    ),
                  ],
                ),
                SizedBox(height: 10),
                Row(
                  crossAxisAlignment: CrossAxisAlignment.center,
                  mainAxisAlignment: MainAxisAlignment.end,
                  children: <Widget>[
                    ElevatedButton(
                      onPressed: () {
                        initPlatformState();
                      },
                      child: Text('Refresh', style: TextStyle(color: Colors.white)),
                    ),
                    SizedBox(width: 20),
                    ElevatedButton(
                      style: ElevatedButton.styleFrom(backgroundColor: _connected ? Colors.red : Colors.green),
                      onPressed: _connected ? _disconnect : _connect,
                      child: Text(_connected ? 'Disconnect' : 'Connect', style: TextStyle(color: Colors.white)),
                    ),
                  ],
                ),
                Padding(
                  padding: const EdgeInsets.only(left: 10.0, right: 10.0, top: 50),
                  child: ElevatedButton(
                    style: ElevatedButton.styleFrom(backgroundColor: Colors.brown),
                    onPressed: _connected ? _testPrint : null,
                    child: Text('PRINT TEST', style: TextStyle(color: Colors.white)),
                  ),
                ),
              ],
            ),
          ),
        ),
      ),
    );
  }

  List<DropdownMenuItem<BluetoothDevice>> _getDeviceItems() {
    List<DropdownMenuItem<BluetoothDevice>> items = [];
    if (_devices.isEmpty) {
      items.add(DropdownMenuItem(child: Text('NONE')));
    } else {
      _devices.forEach((device) {
        items.add(DropdownMenuItem(child: Text(device.name ?? ''), value: device));
      });
    }
    return items;
  }

  void _connect() {
    if (_device == null) {
      show('No device selected.');
    } else {
      bluetooth.isConnected.then((isConnected) {
        if (!(isConnected ?? false)) {
          bluetooth.connect(_device!).catchError((error) {
            setState(() => _connected = false);
          });
          setState(() => _connected = true);
        }
      });
    }
  }

  void _disconnect() {
    bluetooth.disconnect();
    setState(() => _connected = false);
  }

  Future<void> writeToFile(ByteData data, String path) {
    final buffer = data.buffer;
    return File(path).writeAsBytes(buffer.asUint8List(data.offsetInBytes, data.lengthInBytes));
  }

  void _testPrint() async {
    bluetooth.isConnected.then((isConnected) {
      if (isConnected) {
        bluetooth.printNewLine();
        bluetooth.printCustom("HEADER", 3, 1);
        bluetooth.printNewLine();
        bluetooth.printImage(pathImage!); // path of your image/logo
        bluetooth.printNewLine();
        bluetooth.printLeftRight("LEFT", "RIGHT", 0);
        bluetooth.printLeftRight("LEFT", "RIGHT", 1);
        bluetooth.printLeftRight("LEFT", "RIGHT", 1, format: "%-15s %15s %n");
        bluetooth.printNewLine();
        bluetooth.printLeftRight("LEFT", "RIGHT", 2);
        bluetooth.printLeftRight("LEFT", "RIGHT", 3);
        bluetooth.printLeftRight("LEFT", "RIGHT", 4);
        bluetooth.printNewLine();
        bluetooth.print3Column("Col1", "Col2", "Col3", 1);
        bluetooth.print3Column("Col1", "Col2", "Col3", 1, format: "%-10s %10s %10s %n");
        bluetooth.printNewLine();
        bluetooth.print4Column("Col1", "Col2", "Col3", "Col4", 1);
        bluetooth.print4Column("Col1", "Col2", "Col3", "Col4", 1, format: "%-8s %7s %7s %7s %n");
        bluetooth.printNewLine();
        String testString = " čĆžŽšŠ-H-ščđ";
        bluetooth.printCustom(testString, 1, 1, charset: "windows-1250");
        bluetooth.printLeftRight("Številka:", "18000001", 1, charset: "windows-1250");
        bluetooth.printCustom("Body left", 1, 0);
        bluetooth.printCustom("Body right", 0, 2);
        bluetooth.printNewLine();
        bluetooth.printCustom("Thank You", 2, 1);
        bluetooth.printNewLine();
        bluetooth.printQRcode("Insert Your Own Text to Generate", 200, 200, 1);
        bluetooth.printNewLine();
        bluetooth.printNewLine();
        bluetooth.paperCut();
      }
    });
  }

  Future show(
    String message, {
    Duration duration = const Duration(seconds: 3),
  }) async {
    await Future.delayed(Duration(milliseconds: 100));
    ScaffoldMessenger.of(context).showSnackBar(
      SnackBar(
        content: Text(message, style: TextStyle(color: Colors.white)),
        duration: duration,
      ),
    );
  }
}

说明

  1. 初始化:在 initState 方法中初始化平台状态并加载图像。
  2. 设备列表:通过 getBondedDevices 获取已配对的蓝牙设备列表,并在下拉菜单中显示。
  3. 连接和断开:通过 connectdisconnect 方法连接和断开蓝牙设备。
  4. 打印测试:通过 _testPrint 方法进行打印测试,包括打印文本、图像、二维码等。

希望这个示例能帮助您快速上手 drago_blue_printer 插件。如果有任何问题或需要进一步的帮助,请随时提问。


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

1 回复

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


当然,下面是一个关于如何使用 drago_blue_printer 插件进行蓝牙打印机操作的简单示例代码。这个插件允许你通过蓝牙连接和打印到蓝牙打印机。

首先,确保你已经在 pubspec.yaml 文件中添加了 drago_blue_printer 依赖:

dependencies:
  flutter:
    sdk: flutter
  drago_blue_printer: ^最新版本号  # 请替换为实际最新版本号

然后,运行 flutter pub get 来安装依赖。

接下来,在你的 Flutter 项目中,你可以按照以下步骤使用 drago_blue_printer 插件:

  1. 导入插件
import 'package:drago_blue_printer/drago_blue_printer.dart';
  1. 请求权限和初始化蓝牙适配器

确保你已经请求了必要的权限(例如位置权限,因为蓝牙扫描通常需要它),并初始化蓝牙适配器。

import 'package:permission_handler/permission_handler.dart';

Future<void> initBluetooth() async {
  // 请求位置权限
  var status = await Permission.location.status;
  if (!status.isGranted) {
    status = await Permission.location.request();
    if (!status.isGranted) {
      // 处理权限被拒绝的情况
      return;
    }
  }

  // 初始化蓝牙适配器
  bool isBluetoothEnabled = await DragoBluePrinter.instance.isEnabled();
  if (!isBluetoothEnabled) {
    await DragoBluePrinter.instance.enable();
  }
}
  1. 扫描和连接蓝牙设备
Future<void> scanAndConnect() async {
  // 开始扫描蓝牙设备
  var devices = await DragoBluePrinter.instance.startDiscovery();
  
  // 假设我们已经找到了目标设备,这里简单使用第一个设备作为示例
  if (devices.isNotEmpty) {
    BluetoothDevice device = devices.first;
    
    // 连接到蓝牙设备
    bool isConnected = await DragoBluePrinter.instance.connect(device.address);
    if (isConnected) {
      print("Connected to: ${device.name}");
    } else {
      print("Failed to connect to: ${device.name}");
    }
  } else {
    print("No devices found");
  }
}
  1. 发送数据到打印机
Future<void> printData() async {
  // 假设已经连接到一个蓝牙打印机设备
  String data = "Hello, Bluetooth Printer!";
  
  // 发送数据到打印机
  bool isPrinted = await DragoBluePrinter.instance.sendData(data);
  if (isPrinted) {
    print("Data printed successfully");
  } else {
    print("Failed to print data");
  }
}
  1. 关闭蓝牙连接
Future<void> disconnectAndClose() async {
  // 断开蓝牙连接
  bool isDisconnected = await DragoBluePrinter.instance.disconnect();
  if (isDisconnected) {
    print("Disconnected from Bluetooth printer");
  } else {
    print("Failed to disconnect from Bluetooth printer");
  }

  // 关闭蓝牙适配器(可选)
  bool isDisabled = await DragoBluePrinter.instance.disable();
  if (isDisabled) {
    print("Bluetooth adapter disabled");
  } else {
    print("Failed to disable Bluetooth adapter");
  }
}
  1. 完整示例
import 'package:flutter/material.dart';
import 'package:drago_blue_printer/drago_blue_printer.dart';
import 'package:permission_handler/permission_handler.dart';

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

class MyApp extends StatefulWidget {
  @override
  _MyAppState createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
  @override
  void initState() {
    super.initState();
    initBluetooth();
  }

  Future<void> initBluetooth() async {
    var status = await Permission.location.status;
    if (!status.isGranted) {
      status = await Permission.location.request();
      if (!status.isGranted) {
        return;
      }
    }

    bool isBluetoothEnabled = await DragoBluePrinter.instance.isEnabled();
    if (!isBluetoothEnabled) {
      await DragoBluePrinter.instance.enable();
    }

    // 扫描并连接
    scanAndConnect();
  }

  Future<void> scanAndConnect() async {
    var devices = await DragoBluePrinter.instance.startDiscovery();
    if (devices.isNotEmpty) {
      BluetoothDevice device = devices.first;
      bool isConnected = await DragoBluePrinter.instance.connect(device.address);
      if (isConnected) {
        printData();
      }
    }
  }

  Future<void> printData() async {
    String data = "Hello, Bluetooth Printer!";
    bool isPrinted = await DragoBluePrinter.instance.sendData(data);
    if (isPrinted) {
      disconnectAndClose();
    }
  }

  Future<void> disconnectAndClose() async {
    bool isDisconnected = await DragoBluePrinter.instance.disconnect();
    if (isDisconnected) {
      bool isDisabled = await DragoBluePrinter.instance.disable();
      if (isDisabled) {
        print("Bluetooth operations completed");
      }
    }
  }

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: Text('Flutter Bluetooth Printer Example'),
        ),
        body: Center(
          child: Text('Scanning and printing...'),
        ),
      ),
    );
  }
}

注意:以上代码仅作为示例,并未处理所有可能的错误情况和用户交互。在实际应用中,你需要添加更多的错误处理和用户交互逻辑,以确保应用的健壮性和用户体验。此外,请确保你的蓝牙打印机支持该插件所支持的指令集和格式。

回到顶部