- 修改pubspec.yaml
# 蓝牙打印
blue_thermal_printer: ^1.2.3
- 修改\android\app\src\main\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"/>
- 打印
import 'dart:convert';
import 'dart:typed_data';
import 'package:blue_thermal_printer/blue_thermal_printer.dart';
BlueThermalPrinter bluetooth = BlueThermalPrinter.instance;
BluetoothDevice _device;
void dioPrint() async {
List<BluetoothDevice> devices = await bluetooth.getBondedDevices();
if (devices.isEmpty) {
await YDialogs.showError('请先自行蓝牙配对XXXX打印机', context);
return;
}
setState(() {
_device = devices.firstWhere((d) => d.name.contains('XXXX'));
});
if (_device == null) {
await YDialogs.showError('请先自行蓝牙配对XXXX打印机', context);
return;
}
await printTm('1234567890123', sl);
}
void printTm(String tm, int sl) async {
bool isConnected = await bluetooth.isConnected;
String txt = tm + '中文123';
String data1 = '^XA^FO0,70^BY1.8^BCN,32,N^FD' +
tm +
'^FS^XA^CI28^FO0,110^A@N,22,22^FD' +
txt +
'^FS';
String data2 = '^XA^FO305,70^BY1.8^BCN,32,N^FD' +
tm +
'^FS^XA^CI28^FO305,110^A@N,22,22^FD' +
txt +
'^FS';
String end = '^XZ';
List<int> zpl1 = utf8.encode(data1 + end);
List<int> zpl2 = utf8.encode(data1 + data2 + end);
int times = sl ~/ 2;
int modulo = sl % 2;
if (!isConnected) {
try {
await bluetooth.connect(_device).then((value) async {
for (int i = 1; i <= times; i++) {
await bluetooth.writeBytes(Uint8List.fromList([
...zpl2,
]));
}
if (modulo > 0) {
await bluetooth.writeBytes(Uint8List.fromList([
...zpl1,
]));
}
});
} on PlatformException catch (e) {
switch (e.code.toUpperCase()) {
case 'CONNECTION_TIMEOUT':
await YDialogs.showError('处理超时,确认打印机已开机,重试或靠近设备!', context);
break;
case 'BLUETOOTH_DISABLED':
await YDialogs.showError('请先开启蓝牙!', context);
break;
case 'DEVICE_NOT_FOUND':
await YDialogs.showError('请检查设备配对状态!', context);
break;
case 'CONNECT_ERROR':
await YDialogs.showError('连接失败,请检查设备状态!', context);
break;
default:
await YDialogs.showError('未知错误!', context);
}
return;
}
} else {
for (int i = 1; i <= times; i++) {
await bluetooth.writeBytes(Uint8List.fromList([
...zpl2,
]));
}
if (modulo > 0) {
await bluetooth.writeBytes(Uint8List.fromList([
...zpl1,
]));
}
}
}
}