Flutter蓝牙打印日文插件bluetooth_print_kanji的使用
Flutter蓝牙打印日文插件bluetooth_print_kanji的使用
简介
BluetoothPrint
是一个为 Flutter 开发的蓝牙插件,可以帮助开发者构建蓝牙热敏打印机应用,适用于 iOS 和 Android。(例如,Gprinter pt-280、pt-380、gp-1324、gp-2120 等。)
进行中(请建议)
- [ ] 打印 X,Y 位置
- [ ] 设置纸张大小
- [ ] 更多打印示例
版本
- 4.0.0(Flutter 3.x)
- 3.0.0(Flutter 2.x)
- 2.0.0(Flutter 1.12)
- 1.2.0(Flutter 1.9)
功能
功能 | Android | iOS | 描述 |
---|---|---|---|
扫描 | ✅ | ✅ | 开始扫描低功耗蓝牙设备 |
连接 | ✅ | ✅ | 建立与设备的连接 |
断开连接 | ✅ | ✅ | 取消当前或待处理的设备连接 |
状态 | ✅ | ✅ | 蓝牙设备状态流 |
打印测试消息 | ✅ | ✅ | 打印设备测试消息 |
打印文本 | ✅ | ✅ | 打印自定义文本,支持布局 |
打印图像 | ✅ | ✅ | 打印图像 |
打印二维码 | ✅ | ✅ | 打印二维码,支持更改大小 |
打印条形码 | ✅ | ✅ | 打印条形码 |
使用方法
添加依赖
在 pubspec.yaml
文件中添加 bluetooth_print_kanji
依赖:
dependencies:
flutter:
sdk: flutter
bluetooth_print_kanji:
添加蓝牙权限
我们需要添加使用蓝牙和访问位置的权限。
Android
在 android/app/src/main/AndroidManifest.xml
中添加:
<uses-permission android:name="android.permission.BLUETOOTH" />
<uses-permission android:name="android.permission.BLUETOOTH_SCAN" />
<uses-permission android:name="android.permission.BLUETOOTH_CONNECT" />
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
iOS
在 ios/Runner/Info.plist
中添加:
<key>NSBluetoothAlwaysUsageDescription</key>
<string>需要蓝牙权限</string>
<key>NSBluetoothPeripheralUsageDescription</key>
<string>需要蓝牙权限</string>
<key>NSLocationAlwaysAndWhenInUseUsageDescription</key>
<string>需要位置权限</string>
<key>NSLocationAlwaysUsageDescription</key>
<string>需要位置权限</string>
<key>NSLocationWhenInUseUsageDescription</key>
<string>需要位置权限</string>
初始化 BluetoothPrint
实例
import 'package:bluetooth_print_kanji/bluetooth_print.dart';
import 'package:bluetooth_print_kanji/bluetooth_print_model.dart';
BluetoothPrint bluetoothPrint = BluetoothPrint.instance;
扫描
// 开始扫描
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(),
),
),
连接
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 = {};
List<LineText> list = [];
list.add(LineText(type: LineText.TYPE_TEXT, content: '**********************************************', weight: 1, align: LineText.ALIGN_CENTER, linefeed: 1));
list.add(LineText(type: LineText.TYPE_TEXT, content: '打印单据头', weight: 1, align: LineText.ALIGN_CENTER, fontZoom: 2, linefeed: 1));
list.add(LineText(linefeed: 1));
list.add(LineText(type: LineText.TYPE_TEXT, content: '物资名称规格型号', align: LineText.ALIGN_LEFT, relativeX: 0, relativeX: 0, linefeed: 0));
list.add(LineText(type: LineText.TYPE_TEXT, content: '单位', align: LineText.ALIGN_LEFT, x: 350, relativeX: 0, linefeed: 0));
list.add(LineText(type: LineText.TYPE_TEXT, content: '数量', align: LineText.ALIGN_LEFT, x: 500, relativeX: 0, linefeed: 1));
list.add(LineText(type: LineText.TYPE_TEXT, content: '混凝土C30', align: LineText.ALIGN_LEFT, x: 0, relativeX: 0, linefeed: 0));
list.add(LineText(type: LineText.TYPE_TEXT, content: '吨', align: LineText.ALIGN_LEFT, x: 350, relativeX: 0, linefeed: 0));
list.add(LineText(type: LineText.TYPE_TEXT, content: '12.0', align: LineText.ALIGN_LEFT, x: 500, relativeX: 0, linefeed: 1));
list.add(LineText(type: LineText.TYPE_TEXT, content: '**********************************************', weight: 1, align: LineText.ALIGN_CENTER, linefeed: 1));
list.add(LineText(linefeed: 1));
ByteData data = await rootBundle.load("assets/images/bluetooth_print.png");
List<int> imageBytes = data.buffer.asUint8List(data.offsetInBytes, data.lengthInBytes);
String base64Image = base64Encode(imageBytes);
await bluetoothPrint.printReceipt(config, list);
打印 TSC 命令(标签模式)
Map<String, dynamic> config = {
'width': 40, // 标签宽度,单位 mm
'height': 70, // 标签高度,单位 mm
'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'));
List<LineText> list1 = [];
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);
故障排查
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蓝牙打印日文插件bluetooth_print_kanji的使用的实战教程也可以访问 https://www.itying.com/category-92-b0.html
更多关于Flutter蓝牙打印日文插件bluetooth_print_kanji的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html
bluetooth_print_kanji
是一个 Flutter 插件,用于支持蓝牙打印日文字符。以下是如何在 Flutter 项目中使用这个插件的基本步骤:
1. 添加依赖
首先,在 pubspec.yaml
文件中添加 bluetooth_print_kanji
插件的依赖:
dependencies:
flutter:
sdk: flutter
bluetooth_print_kanji: ^1.0.0 # 请检查最新版本
然后,运行 flutter pub get
来安装依赖。
2. 导入插件
在你的 Dart 文件中导入插件:
import 'package:bluetooth_print_kanji/bluetooth_print_kanji.dart';
3. 初始化蓝牙打印
在使用蓝牙打印功能之前,需要初始化蓝牙适配器:
BluetoothPrintKanji bluetoothPrint = BluetoothPrintKanji();
4. 扫描蓝牙设备
扫描附近的蓝牙设备:
List<BluetoothDevice> devices = await bluetoothPrint.scanDevices();
5. 连接到蓝牙设备
选择一个设备并连接:
BluetoothDevice device = devices[0]; // 选择第一个设备
bool connected = await bluetoothPrint.connect(device);
if (connected) {
print("Connected to ${device.name}");
} else {
print("Failed to connect");
}
6. 打印日文字符
连接成功后,可以开始打印日文字符:
String text = "こんにちは、世界!"; // 要打印的日文字符
await bluetoothPrint.printText(text);
7. 断开连接
打印完成后,断开蓝牙连接:
await bluetoothPrint.disconnect();
8. 处理权限
在使用蓝牙功能时,确保你已经获取了必要的权限。在 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>We need Bluetooth access to connect to the printer</string>
<key>NSBluetoothPeripheralUsageDescription</key>
<string>We need Bluetooth access to connect to the printer</string>
9. 错误处理
在实际使用中,可能会遇到各种错误,如连接失败或打印失败。确保在代码中添加适当的错误处理逻辑。
完整示例
以下是一个完整的示例代码:
import 'package:flutter/material.dart';
import 'package:bluetooth_print_kanji/bluetooth_print_kanji.dart';
class PrintPage extends StatefulWidget {
[@override](/user/override)
_PrintPageState createState() => _PrintPageState();
}
class _PrintPageState extends State<PrintPage> {
BluetoothPrintKanji bluetoothPrint = BluetoothPrintKanji();
List<BluetoothDevice> devices = [];
BluetoothDevice? selectedDevice;
[@override](/user/override)
void initState() {
super.initState();
_scanDevices();
}
Future<void> _scanDevices() async {
devices = await bluetoothPrint.scanDevices();
setState(() {});
}
Future<void> _connectAndPrint() async {
if (selectedDevice == null) return;
bool connected = await bluetoothPrint.connect(selectedDevice!);
if (connected) {
String text = "こんにちは、世界!";
await bluetoothPrint.printText(text);
await bluetoothPrint.disconnect();
} else {
print("Failed to connect");
}
}
[@override](/user/override)
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text("Bluetooth Print Kanji"),
),
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(),
));