Flutter蓝牙打印插件bluetooth_x_print的使用

Flutter蓝牙打印插件bluetooth_x_print的使用

简介

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

待办事项(请建议)

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

版本

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

功能

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

使用方法

示例

您可以查看 示例代码 来了解如何使用此插件。

添加依赖

在 pubspec.yaml 文件中添加依赖项:

dependencies:
  flutter:
    sdk: flutter
  bluetooth_print:
初始化蓝牙打印实例
import 'package:bluetooth_x_print/bluetooth_print.dart';
import 'package:bluetooth_x_print/bluetooth_print_model.dart';

BluetoothPrint bluetoothPrint = BluetoothPrint.instance;
扫描蓝牙设备
// 开始扫描
bluetoothPrint.startScan(timeout: Duration(seconds: 4));

// 获取设备列表
StreamBuilder<List<BluetoothDevice>>(
    stream: bluetoothPrint.scanResults,
    initialData: [],
    builder: (c, snapshot) => Column(
      children: snapshot.data.map((d) => ListTile(
        title: Text(d.name ?? ''),
        subtitle: Text(d.address),
        onTap: () async {
          setState(() {
            _device = d;
          });
        },
        trailing: _device != null && _device.address == d.address ? Icon(
          Icons.check,
          color: Colors.green,
        ) : null,
      )).toList(),
    ),
  ),
连接蓝牙设备
await bluetoothPrint.connect(_device);
断开蓝牙连接
await bluetoothPrint.disconnect();
监听蓝牙设备状态
bluetoothPrint.state.listen((state) {
  print('当前设备状态: $state');

  switch (state) {
    case BluetoothPrint.CONNECTED:
      setState(() {
        _connected = true;
      });
      break;
    case BluetoothPrint.DISCONNECTED:
      setState(() {
        _connected = false;
      });
      break;
    default:
      break;
  }
});
打印 ESC 命令(收据模式)
Map<String, dynamic> config = Map();
List<LineText> list = 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);
打印 TSC 命令(标签模式)
Map<String, dynamic> config = Map();
config['width'] = 40; // 标签宽度,单位 mm
config['height'] = 70; // 标签高度,单位 mm
config['gap'] = 2; // 标签间隔,单位 mm

// x、y 坐标位置,单位 dpi,1mm=8dpi
List<LineText> list = 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'));

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

await bluetoothPrint.printLabel(config, list);
await bluetoothPrint.printLabel(config, list1);

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

1 回复

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


bluetooth_x_print 是一个用于 Flutter 的蓝牙打印插件,允许开发者通过蓝牙连接打印机并发送打印指令。以下是使用该插件的基本步骤:

1. 添加依赖

首先,在 pubspec.yaml 文件中添加 bluetooth_x_print 依赖:

dependencies:
  flutter:
    sdk: flutter
  bluetooth_x_print: ^0.1.0  # 请检查最新版本

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

2. 导入包

在需要使用的 Dart 文件中导入 bluetooth_x_print 包:

import 'package:bluetooth_x_print/bluetooth_x_print.dart';

3. 初始化插件

在使用插件之前,确保你已经初始化了插件:

BluetoothXPrint bluetoothXPrint = BluetoothXPrint();

4. 扫描蓝牙设备

你可以使用 scanDevices() 方法来扫描附近的蓝牙设备:

List<BluetoothDevice> devices = await bluetoothXPrint.scanDevices();

BluetoothDevice 对象包含设备的名称和地址等信息。

5. 连接蓝牙设备

选择扫描到的设备并连接:

bool isConnected = await bluetoothXPrint.connect(device.address);

device.address 是蓝牙设备的地址,isConnected 表示连接是否成功。

6. 发送打印指令

连接成功后,你可以发送打印指令。bluetooth_x_print 插件支持多种打印指令,例如文本、图片等。

例如,打印一段文本:

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

打印图片:

Uint8List imageBytes = await _getImageBytes(); // 获取图片的字节数据
await bluetoothXPrint.printImage(imageBytes);

7. 断开连接

打印完成后,断开蓝牙连接:

await bluetoothXPrint.disconnect();

示例代码

以下是一个完整的示例代码:

import 'package:flutter/material.dart';
import 'package:bluetooth_x_print/bluetooth_x_print.dart';
import 'dart:typed_data';

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

class _PrintPageState extends State<PrintPage> {
  BluetoothXPrint bluetoothXPrint = BluetoothXPrint();
  List<BluetoothDevice> devices = [];
  BluetoothDevice? selectedDevice;

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

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

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

    bool isConnected = await bluetoothXPrint.connect(selectedDevice!.address);
    if (isConnected) {
      await bluetoothXPrint.printText("Hello, World!");
      await bluetoothXPrint.disconnect();
    }
  }

  [@override](/user/override)
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Bluetooth Print'),
      ),
      body: Column(
        children: [
          DropdownButton<BluetoothDevice>(
            value: selectedDevice,
            items: devices.map((device) {
              return DropdownMenuItem(
                value: device,
                child: Text(device.name),
              );
            }).toList(),
            onChanged: (device) {
              setState(() {
                selectedDevice = device;
              });
            },
          ),
          ElevatedButton(
            onPressed: connectAndPrint,
            child: Text('Print'),
          ),
        ],
      ),
    );
  }
}

void main() => runApp(MaterialApp(
  home: PrintPage(),
));
回到顶部