Flutter蓝牙打印插件huaji_bluetooth_print的使用

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

Flutter蓝牙打印插件huaji_bluetooth_print的使用

Introduction

BluetoothPrint 是一个用于 Flutter 的蓝牙插件,可以帮助开发者为 iOS 和 Android 平台构建蓝牙热敏打印机应用程序。(例如,Gprinter pt-280、pt-380、gp-1324、gp-2120 等。)

Underway(请建议)

  • [ ] 打印 x, y 坐标位置
  • [ ] 设置纸张大小
  • [ ] 更多打印示例

verison

  • 3.0.0(适用于 flutter 2.x)
  • 2.0.0(适用于 flutter 1.12)
  • 1.2.0(适用于 flutter 1.9)

Features

功能 Android iOS 描述
扫描设备 开始扫描低功耗蓝牙设备。
连接设备 建立与设备的连接。
断开连接 取消与设备的活动或待处理连接。
监听状态 监听蓝牙设备的状态变化流。
打印测试信息 打印设备测试信息。
打印文本 打印自定义文本,支持布局。
打印图片 打印图片。
打印二维码 打印二维码,支持调整大小。
打印条形码 打印条形码。

Usage

要使用此插件:

  1. pubspec.yaml 文件中添加依赖项。
dependencies:
  flutter:
    sdk: flutter
  huaji_bluetooth_print:
  1. 初始化 HuajiBluetoothPrint 实例。
import 'package:huaji_bluetooth_print/huaji_bluetooth_print.dart';
import 'package:huaji_bluetooth_print/bluetooth_print_model.dart';

HuajiBluetoothPrint bluetoothPrint = HuajiBluetoothPrint.instance;

Scan

开始扫描蓝牙设备:

// 开始扫描
bluetoothPrint.startScan(timeout: Duration(seconds: 4));

// 获取设备列表
StreamBuilder<List<BluetoothDevice>>(
    stream: bluetoothPrint.scanResults,
    initialData: [],
    builder: (context, snapshot) => Column(
      children: snapshot.data.map((device) => ListTile(
        title: Text(device.name ?? ''),
        subtitle: Text(device.address),
        onTap: () async {
          setState(() {
            _device = device;
          });
        },
        trailing: _device != null && _device.address == device.address ? Icon(
          Icons.check,
          color: Colors.green,
        ) : null,
      )).toList(),
    ),
  ),

Connect

连接到指定设备:

await bluetoothPrint.connect(_device);

Disconnect

断开与设备的连接:

await bluetoothPrint.disconnect();

Listen State

监听设备状态变化:

bluetoothPrint.state.listen((state) {
  print('当前设备状态: $state');

  switch (state) {
    case HuajiBluetoothPrint.CONNECTED:
      setState(() {
        _connected = true;
      });
      break;
    case HuajiBluetoothPrint.DISCONNECTED:
      setState(() {
        _connected = false;
      });
      break;
    default:
      break;
  }
});

Print ESC Command (Receipt Mode)

打印 ESC 命令(收据模式):

Map<String, dynamic> config = {};
List<LineText> list = [];

list.add(LineText(type: LineText.TYPE_TEXT, content: 'A Title', weight: 1, align: LineText.ALIGN_CENTER, linefeed: 1));
list.add(LineText(type: LineText.TYPE_TEXT, content: 'this is conent left', weight: 0, align: LineText.ALIGN_LEFT, linefeed: 1));
list.add(LineText(type: LineText.TYPE_TEXT, content: 'this is conent right', align: LineText.ALIGN_RIGHT, linefeed: 1));
list.add(LineText(linefeed: 1));
list.add(LineText(type: LineText.TYPE_BARCODE, content: 'A12312112', size: 10, align: LineText.ALIGN_CENTER, linefeed: 1));
list.add(LineText(linefeed: 1));
list.add(LineText(type: LineText.TYPE_QRCODE, content: 'qrcode i', size: 10, align: LineText.ALIGN_CENTER, linefeed: 1));
list.add(LineText(linefeed: 1));

ByteData data = await rootBundle.load("assets/images/guide3.png");
List<int> imageBytes = data.buffer.asUint8List(data.offsetInBytes, data.lengthInBytes);
String base64Image = base64Encode(imageBytes);
list.add(LineText(type: LineText.TYPE_IMAGE, content: base64Image, align: LineText.ALIGN_CENTER, linefeed: 1));

await bluetoothPrint.printReceipt(config, list);

Print TSC Command (Label Mode)

打印 TSC 命令(标签模式):

Map<String, dynamic> config = {};
config['width'] = 40; // 标签宽度,单位 mm
config['height'] = 70; // 标签高度,单位 mm
config['gap'] = 2; // 标签间隔,单位 mm

List<LineText> list = [];
list.add(LineText(type: LineText.TYPE_TEXT, x: 10, y: 10, content: 'A Title'));
list.add(LineText(type: LineText.TYPE_TEXT, x: 10, y: 40, content: 'this is content'));
list.add(LineText(type: LineText.TYPE_QRCODE, x: 10, y: 70, content: 'qrcode i\n'));
list.add(LineText(type: LineText.TYPE_BARCODE, x: 10, y: 190, content: 'qrcode i\n'));

ByteData data = await rootBundle.load("assets/images/guide3.png");
List<int> imageBytes = data.buffer.asUint8List(data.offsetInBytes, data.lengthInBytes);
String base64Image = base64Encode(imageBytes);
list.add(LineText(type: LineText.TYPE_IMAGE, x: 10, y: 10, content: base64Image));

await bluetoothPrint.printLabel(config, list);

Troubleshooting

iOS 导入第三方库

.podspec 文件中添加以下内容:

# .a 文件名必须以 lib 开头,例如 'libXXX.a'
s.vendored_libraries = '**/*.a'
错误:State restoration of CBCentralManager is only allowed for applications that have specified the "bluetooth-central" background mode

Info.plist 中添加以下配置:

<key>NSBluetoothAlwaysUsageDescription</key>
<string>允许应用使用蓝牙?</string>
<key>NSBluetoothPeripheralUsageDescription</key>
<string>允许应用使用蓝牙?</string>
<key>UIBackgroundModes</key>
<array>
    <string>bluetooth-central</string>
    <string>bluetooth-peripheral</string>
</array>

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

1 回复

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


huaji_bluetooth_print 是一个用于在 Flutter 应用中实现蓝牙打印功能的插件。它支持与蓝牙打印机进行通信,并发送打印指令。以下是如何使用 huaji_bluetooth_print 插件的基本步骤:

1. 添加依赖

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

dependencies:
  flutter:
    sdk: flutter
  huaji_bluetooth_print: ^1.0.0  # 请使用最新版本

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

2. 配置权限

在 Android 和 iOS 上使用蓝牙功能需要相应的权限。

Android

AndroidManifest.xml 文件中添加以下权限:

<uses-permission android:name="android.permission.BLUETOOTH"/>
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN"/>
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>

iOS

Info.plist 文件中添加以下权限:

<key>NSBluetoothAlwaysUsageDescription</key>
<string>我们需要访问蓝牙以连接打印机</string>
<key>NSBluetoothPeripheralUsageDescription</key>
<string>我们需要访问蓝牙以连接打印机</string>

3. 初始化插件

在你的 Dart 代码中导入并初始化 huaji_bluetooth_print 插件:

import 'package:huaji_bluetooth_print/huaji_bluetooth_print.dart';

final HuajiBluetoothPrint bluetoothPrint = HuajiBluetoothPrint.instance;

4. 扫描蓝牙设备

使用 scan 方法来扫描附近的蓝牙设备:

List<BluetoothDevice> devices = await bluetoothPrint.scan();

5. 连接蓝牙设备

选择要连接的设备并调用 connect 方法:

BluetoothDevice selectedDevice = devices[0]; // 选择第一个设备
bool isConnected = await bluetoothPrint.connect(selectedDevice);
if (isConnected) {
  print("Connected to ${selectedDevice.name}");
} else {
  print("Failed to connect");
}

6. 发送打印指令

连接成功后,你可以发送打印指令。例如,打印一段文本:

String text = "Hello, World!";
await bluetoothPrint.printText(text);

7. 断开连接

打印完成后,断开与蓝牙设备的连接:

await bluetoothPrint.disconnect();

8. 处理错误

在实际使用中,可能会遇到各种错误,例如连接失败、打印失败等。你可以使用 try-catch 来捕获并处理这些错误:

try {
  await bluetoothPrint.connect(selectedDevice);
  await bluetoothPrint.printText("Hello, World!");
} catch (e) {
  print("Error: $e");
}

9. 其他功能

huaji_bluetooth_print 插件还支持其他功能,例如打印图片、设置打印格式等。你可以参考插件的文档或源码来了解更多细节。

示例代码

以下是一个完整的示例代码,展示了如何使用 huaji_bluetooth_print 插件进行蓝牙打印:

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

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

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

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

class _BluetoothPrintScreenState extends State<BluetoothPrintScreen> {
  final HuajiBluetoothPrint bluetoothPrint = HuajiBluetoothPrint.instance;
  List<BluetoothDevice> devices = [];
  BluetoothDevice? selectedDevice;

  [@override](/user/override)
  void initState() {
    super.initState();
    scanDevices();
  }

  Future<void> scanDevices() async {
    devices = await bluetoothPrint.scan();
    setState(() {});
  }

  Future<void> connectAndPrint() async {
    if (selectedDevice == null) return;

    try {
      bool isConnected = await bluetoothPrint.connect(selectedDevice!);
      if (isConnected) {
        await bluetoothPrint.printText("Hello, World!");
        await bluetoothPrint.disconnect();
      } else {
        print("Failed to connect");
      }
    } catch (e) {
      print("Error: $e");
    }
  }

  [@override](/user/override)
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text("Bluetooth Print"),
      ),
      body: Column(
        children: [
          DropdownButton<BluetoothDevice>(
            value: selectedDevice,
            onChanged: (BluetoothDevice? device) {
              setState(() {
                selectedDevice = device;
              });
            },
            items: devices.map((BluetoothDevice device) {
              return DropdownMenuItem<BluetoothDevice>(
                value: device,
                child: Text(device.name),
              );
            }).toList(),
          ),
          ElevatedButton(
            onPressed: connectAndPrint,
            child: Text("Print"),
          ),
        ],
      ),
    );
  }
}
回到顶部
AI 助手
你好,我是IT营的 AI 助手
您可以尝试点击下方的快捷入口开启体验!