Flutter蓝牙打印插件blue_print_pos的使用

Flutter蓝牙打印插件blue_print_pos的使用

介绍

该插件用于在Android/iOS上使用蓝牙打印机。支持文本、图像、添加新行或虚线行以及二维码。

使用

初始化

BluePrintPos bluePrintPos = BluePrintPos.instance;

扫描蓝牙打印机

bluePrintPos.scan();

连接蓝牙打印机

bluePrintPos.connect(device);

打印文本

在方法 addText(text, {size, style, alignment}) 中,您可以修改大小、样式和对齐方式。

ReceiptSectionText receiptText = ReceiptSectionText();
receiptText.addText('MY STORE', size: ReceiptTextSizeType.medium, style: ReceiptTextStyleType.bold);

打印左右对齐的文本

receiptText.addLeftRightText('Time', '04/06/21, 10:00');

打印图像

final ByteData logoBytes = await rootBundle.load('assets/logo.jpg');
receiptText.addImage(
  base64.encode(Uint8List.view(logoBytes.buffer)),
  width: 150,
);

添加新行

receiptText.addSpacer();

添加带虚线的新行

receiptText.addSpacer(useDashed: true);

入门指南

Android

<code>minSdkVersion</code><strong>android/app/build.gradle</strong> 中更改为 19

android {
  defaultConfig {
     minSdkVersion 19
  }
}

添加蓝牙和位置访问权限到 <strong>android/app/src/main/AndroidManifest.xml</strong>

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

iOS

<strong>ios/Runner/Info.plist</strong> 中添加信息键

<key>NSBluetoothAlwaysUsageDescription</key>  
<string>Need BLE permission</string>  
<key>NSBluetoothPeripheralUsageDescription</key>  
<string>Need BLE permission</string>  
<key>NSLocationAlwaysAndWhenInUseUsageDescription</key>  
<string>Need Location permission</string>  
<key>NSLocationAlwaysUsageDescription</key>  
<string>Need Location permission</string>  
<key>NSLocationWhenInUseUsageDescription</key>  
<string>Need Location permission</string>

感谢

参考和依赖创建了此插件


示例代码

import 'dart:convert';
import 'dart:typed_data';

import 'package:blue_print_pos/blue_print_pos.dart';
import 'package:blue_print_pos/models/models.dart';
import 'package:blue_print_pos/receipt/receipt.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';

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

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

class _MyAppState extends State<MyApp> {
  final BluePrintPos _bluePrintPos = BluePrintPos.instance;
  List<BlueDevice> _blueDevices = [];
  BlueDevice? _selectedDevice;
  bool _isLoading = false;
  int _loadingAtIndex = -1;

  [@override](/user/override)
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: const Text('Blue Print Pos'),
        ),
        body: SafeArea(
          child: _isLoading && _blueDevices.isEmpty
              ? const Center(
                  child: CircularProgressIndicator(
                    valueColor: AlwaysStoppedAnimation<Color>(Colors.blue),
                  ),
                )
              : _blueDevices.isNotEmpty
                  ? SingleChildScrollView(
                      child: Column(
                        crossAxisAlignment: CrossAxisAlignment.start,
                        children: [
                          Column(
                            children: List<Widget>.generate(_blueDevices.length, (int index) {
                              return Row(
                                children: [
                                  Expanded(
                                    child: GestureDetector(
                                      onTap: _blueDevices[index].address == (_selectedDevice?.address ?? '')
                                          ? _onDisconnectDevice
                                          : () => _onSelectDevice(index),
                                      child: Padding(
                                        padding: const EdgeInsets.all(8.0),
                                        child: Column(
                                          crossAxisAlignment: CrossAxisAlignment.start,
                                          children: [
                                            Text(
                                              _blueDevices[index].name,
                                              style: TextStyle(
                                                color: _selectedDevice?.address == _blueDevices[index].address
                                                    ? Colors.blue
                                                    : Colors.black,
                                                fontSize: 20,
                                                fontWeight: FontWeight.w500,
                                              ),
                                            ),
                                            Text(
                                              _blueDevices[index].address,
                                              style: TextStyle(
                                                color: _selectedDevice?.address == _blueDevices[index].address
                                                    ? Colors.blueGrey
                                                    : Colors.grey,
                                                fontSize: 14,
                                                fontWeight: FontWeight.w500,
                                              ),
                                            ),
                                          ],
                                        ),
                                      ),
                                    ),
                                  ),
                                  if (_loadingAtIndex == index && _isLoading)
                                    Container(
                                      height: 24.0,
                                      width: 24.0,
                                      margin: const EdgeInsets.only(right: 8.0),
                                      child: const CircularProgressIndicator(
                                        valueColor: AlwaysStoppedAnimation<Color>(
                                          Colors.blue,
                                        ),
                                      ),
                                    ),
                                  if (!_isLoading && _blueDevices[index].address == (_selectedDevice?.address ?? ''))
                                    TextButton(
                                      onPressed: _onPrintReceipt,
                                      child: Container(
                                        color: _selectedDevice == null
                                            ? Colors.grey
                                            : Colors.blue,
                                        padding: const EdgeInsets.all(8.0),
                                        child: const Text(
                                          'Test Print',
                                          style: TextStyle(color: Colors.white),
                                        ),
                                      ),
                                      style: ButtonStyle(
                                        backgroundColor: MaterialStateProperty.resolveWith<Color>(
                                          (Set<MaterialState> states) {
                                            if (states.contains(MaterialState.pressed)) {
                                              return Theme.of(context).colorScheme.primary.withOpacity(0.5);
                                            }
                                            return Theme.of(context).primaryColor;
                                          },
                                        ),
                                      ),
                                    ),
                                ],
                              );
                            }),
                          ),
                        ],
                      ),
                    )
                  : Center(
                      child: Column(
                        mainAxisAlignment: MainAxisAlignment.center,
                        children: const [
                          Text(
                            'Scan bluetooth device',
                            style: TextStyle(fontSize: 24, color: Colors.blue),
                          ),
                          Text(
                            'Press button scan',
                            style: TextStyle(fontSize: 14, color: Colors.grey),
                          ),
                        ],
                      ),
                    ),
        ),
        floatingActionButton: FloatingActionButton(
          onPressed: _isLoading ? null : _onScanPressed,
          child: const Icon(Icons.search),
          backgroundColor: _isLoading ? Colors.grey : Colors.blue,
        ),
      ),
    );
  }

  Future<void> _onScanPressed() async {
    setState(() => _isLoading = true);
    _bluePrintPos.scan().then((List<BlueDevice> devices) {
      if (devices.isNotEmpty) {
        setState(() {
          _blueDevices = devices;
          _isLoading = false;
        });
      } else {
        setState(() => _isLoading = false);
      }
    });
  }

  void _onDisconnectDevice() {
    _bluePrintPos.disconnect().then((ConnectionStatus status) {
      if (status == ConnectionStatus.disconnect) {
        setState(() {
          _selectedDevice = null;
        });
      }
    });
  }

  void _onSelectDevice(int index) {
    setState(() {
      _isLoading = true;
      _loadingAtIndex = index;
    });
    final BlueDevice blueDevice = _blueDevices[index];
    _bluePrintPos.connect(blueDevice).then((ConnectionStatus status) {
      if (status == ConnectionStatus.connected) {
        setState(() => _selectedDevice = blueDevice);
      } else if (status == ConnectionStatus.timeout) {
        _onDisconnectDevice();
      } else {
        print('$runtimeType - something wrong');
      }
      setState(() => _isLoading = false);
    });
  }

  Future<void> _onPrintReceipt() async {
    /// 示例打印图像
    final ByteData logoBytes = await rootBundle.load(
      'assets/logo.jpg',
    );

    /// 示例打印文本
    final ReceiptSectionText receiptText = ReceiptSectionText();
    receiptText.addImage(
      base64.encode(Uint8List.view(logoBytes.buffer)),
      width: 150,
    );
    receiptText.addSpacer();
    receiptText.addText(
      'MY STORE',
      size: ReceiptTextSizeType.medium,
      style: ReceiptTextStyleType.bold,
    );
    receiptText.addText(
      'Black White Street, Jakarta, Indonesia',
      size: ReceiptTextSizeType.small,
    );
    receiptText.addSpacer(useDashed: true);
    receiptText.addLeftRightText('Time', '04/06/21, 10:00');
    receiptText.addSpacer(useDashed: true);
    receiptText.addLeftRightText(
      'Apple 1kg',
      'Rp30.000',
      leftStyle: ReceiptTextStyleType.normal,
      rightStyle: ReceiptTextStyleType.bold,
    );
    receiptText.addSpacer(useDashed: true);
    receiptText.addLeftRightText(
      'TOTAL',
      'Rp30.000',
      leftStyle: ReceiptTextStyleType.normal,
      rightStyle: ReceiptTextStyleType.bold,
    );
    receiptText.addSpacer(useDashed: true);
    receiptText.addLeftRightText(
      'Payment',
      'Cash',
      leftStyle: ReceiptTextStyleType.normal,
      rightStyle: ReceiptTextStyleType.normal,
    );
    receiptText.addSpacer(count: 2);

    await _bluePrintPos.printReceiptText(receiptText);

    /// 示例打印二维码
    await _bluePrintPos.printQR('www.google.com', size: 250);

    /// 二维码后的文本
    final ReceiptSectionText receiptSecondText = ReceiptSectionText();
    receiptSecondText.addText('Powered by ayeee',
        size: ReceiptTextSizeType.small);
    receiptSecondText.addSpacer();
    await _bluePrintPos.printReceiptText(receiptSecondText, feedCount: 1);
  }
}

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

1 回复

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


关于Flutter蓝牙打印插件blue_print_pos的使用,以下是一个简单的代码示例,展示了如何集成和使用该插件进行蓝牙打印。

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

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

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

接下来,在你的Flutter项目中,你可以按照以下步骤使用blue_print_pos插件进行蓝牙打印:

  1. 导入插件

在你的Dart文件中,导入blue_print_pos插件:

import 'package:blue_print_pos/blue_print_pos.dart';
import 'package:flutter/material.dart';
  1. 初始化插件并扫描蓝牙设备

在你的主页面或需要扫描蓝牙设备的页面中,初始化BluePrintPos插件并扫描蓝牙设备:

class BluetoothPrintPage extends StatefulWidget {
  @override
  _BluetoothPrintPageState createState() => _BluetoothPrintPageState();
}

class _BluetoothPrintPageState extends State<BluetoothPrintPage> {
  late BluePrintPos bluePrintPos;
  List<BluetoothDevice> devices = [];

  @override
  void initState() {
    super.initState();
    bluePrintPos = BluePrintPos();
    bluePrintPos.initialize().then((_) {
      bluePrintPos.startScan().listen((device) {
        setState(() {
          devices.add(device);
        });
      });
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Bluetooth Print'),
      ),
      body: Column(
        children: [
          Expanded(
            child: ListView.builder(
              itemCount: devices.length,
              itemBuilder: (context, index) {
                return ListTile(
                  title: Text(devices[index].name),
                  onTap: () {
                    // 连接到设备并打印
                    connectAndPrint(devices[index]);
                  },
                );
              },
            ),
          ),
        ],
      ),
    );
  }

  void connectAndPrint(BluetoothDevice device) async {
    await bluePrintPos.connect(device.address);
    await bluePrintPos.printText("Hello, Bluetooth Print!\n");
    await bluePrintPos.disconnect();
  }

  @override
  void dispose() {
    bluePrintPos.stopScan();
    super.dispose();
  }
}
  1. 运行应用

确保你的设备支持蓝牙,并且已经开启蓝牙功能。运行你的Flutter应用,你应该能够看到扫描到的蓝牙设备列表,并且点击设备后可以进行连接并打印文本。

注意

  • 在实际使用中,你可能需要处理更多的错误和异常情况,比如连接失败、打印失败等。
  • blue_print_pos插件的具体API和用法可能会随着版本的更新而有所变化,请参考最新的官方文档和示例代码。
  • 打印的内容格式(如文本、图片、条形码等)取决于你使用的蓝牙打印机支持的指令集,你可能需要查阅打印机的说明书或开发者文档来了解如何发送正确的打印指令。

以上代码提供了一个基本的框架,展示了如何在Flutter中使用blue_print_pos插件进行蓝牙打印。你可以根据自己的需求进行进一步的定制和扩展。

回到顶部