Flutter蓝牙打印机插件maswend_bt_printer的使用
Flutter蓝牙打印机插件maswend_bt_printer的使用
该库允许使用蓝牙打印机打印收据(仅限Android)。它支持58毫米和80毫米的蓝牙打印机。
此插件不使用位置权限。因此,遵循了Android 10的谷歌政策。
插件依赖
- esc_pos_utils 包用于打印收据。
- image 包用于打印图像。
简单票据样式示例
List<int> testTicket() {
final List<int> bytes = [];
// 使用默认配置文件
final profile = await CapabilityProfile.load();
final generator = Generator(PaperSize.mm80, profile);
List<int> bytes = [];
bytes += generator.text(
'常规文本: aA bB cC dD eE fF gG hH iI jJ kK lL mM nN oO pP qQ rR sS tT uU vV wW xX yY zZ');
bytes += generator.text('特殊字符1: àÀ èÈ éÉ ûÛ üÜ çÇ ôÔ',
styles: PosStyles(codeTable: PosCodeTable.westEur));
bytes += generator.text('特殊字符2: blåbærgrød',
styles: PosStyles(codeTable: PosCodeTable.westEur));
bytes += generator.text('粗体文本', styles: PosStyles(bold: true));
bytes += generator.text('反向文本', styles: PosStyles(reverse: true));
bytes += generator.text('下划线文本',
styles: PosStyles(underline: true), linesAfter: 1);
bytes += generator.text('左对齐', styles: PosStyles(align: PosAlign.left));
bytes += generator.text('居中对齐', styles: PosStyles(align: PosAlign.center));
bytes += generator.text('右对齐',
styles: PosStyles(align: PosAlign.right), linesAfter: 1);
bytes += generator.text('文本大小200%',
styles: PosStyles(
height: PosTextSize.size2,
width: PosTextSize.size2,
));
bytes += generator.feed(2);
bytes += generator.cut();
return bytes;
}
更多示例可以在这里找到:esc_pos_utils。
如何帮助
- 测试你的打印机并将其添加到测试打印机列表中。
- 测试并报告错误。
- 分享你认为可以改进的想法(代码优化、新功能等)。
- 欢迎提交PR!
已测试的打印机
以下是与本库一起测试的一些打印机。请将您测试过的型号添加进来,以维护和改进本库,并帮助其他人选择合适的打印机。
完整的示例可以在示例项目中找到。
完整示例代码
示例代码
import 'dart:async';
import 'package:maswend_bt_printer/maswend_bt_printer.dart';
import 'package:esc_pos_utils_plus/esc_pos_utils.dart';
import 'package:flutter/material.dart';
void main() {
runApp(MyApp());
}
class MyApp extends StatefulWidget {
[@override](/user/override)
_MyAppState createState() => _MyAppState();
}
class _MyAppState extends State<MyApp> {
[@override](/user/override)
void initState() {
super.initState();
}
bool connected = false;
List availableBluetoothDevices = [];
Future<void> getBluetooth() async {
final List? bluetooths = await MaswendBTPrinter.getBluetooths;
print("Print $bluetooths");
setState(() {
availableBluetoothDevices = bluetooths!;
});
}
Future<void> setConnect(String mac) async {
final String? result = await MaswendBTPrinter.connect(mac);
print("state connected $result");
if (result == "true") {
setState(() {
connected = true;
});
}
}
Future<void> printTicket() async {
String? isConnected = await MaswendBTPrinter.connectionStatus;
if (isConnected == "true") {
List<int> bytes = await getTicket();
final result = await MaswendBTPrinter.writeBytes(bytes);
print("Print $result");
} else {
// 处理未连接的情况
}
}
Future<void> printGraphics() async {
String? isConnected = await MaswendBTPrinter.connectionStatus;
if (isConnected == "true") {
List<int> bytes = await getGraphicsTicket();
final result = await MaswendBTPrinter.writeBytes(bytes);
print("Print $result");
} else {
// 处理未连接的情况
}
}
Future<List<int>> getGraphicsTicket() async {
List<int> bytes = [];
CapabilityProfile profile = await CapabilityProfile.load();
final generator = Generator(PaperSize.mm80, profile);
// 使用原生函数打印二维码
bytes += generator.qrcode('mwend.com');
bytes += generator.hr();
// 使用原生函数打印条形码
final List<int> barData = [1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 4];
bytes += generator.barcode(Barcode.upcA(barData));
bytes += generator.cut();
return bytes;
}
Future<List<int>> getTicket() async {
List<int> bytes = [];
CapabilityProfile profile = await CapabilityProfile.load();
final generator = Generator(PaperSize.mm80, profile);
bytes += generator.text("Demo Toko",
styles: PosStyles(
align: PosAlign.center,
height: PosTextSize.size2,
width: PosTextSize.size2,
),
linesAfter: 1);
bytes += generator.text("JL.Bypass Ujungaris - Widasari - Indramayu",
styles: PosStyles(align: PosAlign.center));
bytes += generator.text('Tel: +628991585001',
styles: PosStyles(align: PosAlign.center));
bytes += generator.hr();
bytes += generator.row([
PosColumn(
text: 'No',
width: 1,
styles: PosStyles(align: PosAlign.left, bold: true)),
PosColumn(
text: 'Produk',
width: 5,
styles: PosStyles(align: PosAlign.left, bold: true)),
PosColumn(
text: 'Harga',
width: 2,
styles: PosStyles(align: PosAlign.center, bold: true)),
PosColumn(
text: 'Jml',
width: 2,
styles: PosStyles(align: PosAlign.center, bold: true)),
PosColumn(
text: 'Total',
width: 2,
styles: PosStyles(align: PosAlign.right, bold: true)),
]);
bytes += generator.row([
PosColumn(text: "1", width: 1),
PosColumn(
text: "Mie Indomie",
width: 5,
styles: PosStyles(
align: PosAlign.left,
)),
PosColumn(
text: "3000",
width: 2,
styles: PosStyles(
align: PosAlign.center,
)),
PosColumn(text: "1", width: 2, styles: PosStyles(align: PosAlign.center)),
PosColumn(
text: "3000", width: 2, styles: PosStyles(align: PosAlign.right)),
]);
bytes += generator.row([
PosColumn(text: "2", width: 1),
PosColumn(
text: "Kecap Sedap",
width: 5,
styles: PosStyles(
align: PosAlign.left,
)),
PosColumn(
text: "1500",
width: 2,
styles: PosStyles(
align: PosAlign.center,
)),
PosColumn(text: "2", width: 2, styles: PosStyles(align: PosAlign.center)),
PosColumn(
text: "3000", width: 2, styles: PosStyles(align: PosAlign.right)),
]);
bytes += generator.row([
PosColumn(text: "3", width: 1),
PosColumn(
text: "Pantine",
width: 5,
styles: PosStyles(
align: PosAlign.left,
)),
PosColumn(
text: "500",
width: 2,
styles: PosStyles(
align: PosAlign.center,
)),
PosColumn(text: "4", width: 2, styles: PosStyles(align: PosAlign.center)),
PosColumn(
text: "2000", width: 2, styles: PosStyles(align: PosAlign.right)),
]);
bytes += generator.row([
PosColumn(text: "4", width: 1),
PosColumn(
text: "Kopi Mix",
width: 5,
styles: PosStyles(
align: PosAlign.left,
)),
PosColumn(
text: "1500",
width: 2,
styles: PosStyles(
align: PosAlign.center,
)),
PosColumn(text: "2", width: 2, styles: PosStyles(align: PosAlign.center)),
PosColumn(
text: "3000", width: 2, styles: PosStyles(align: PosAlign.right)),
]);
bytes += generator.hr();
bytes += generator.row([
PosColumn(
text: 'TOTAL',
width: 6,
styles: PosStyles(
align: PosAlign.left,
height: PosTextSize.size4,
width: PosTextSize.size4,
)),
PosColumn(
text: "11000",
width: 6,
styles: PosStyles(
align: PosAlign.right,
height: PosTextSize.size4,
width: PosTextSize.size4,
)),
]);
bytes += generator.hr(ch: '=', linesAfter: 1);
// ticket.feed(2);
bytes += generator.text('Terimakasih!',
styles: PosStyles(align: PosAlign.center, bold: true));
bytes += generator.text("26-11-2020 15:22:45",
styles: PosStyles(align: PosAlign.center), linesAfter: 1);
bytes += generator.text(
'Note: Barang Yang Dibeli Tidak Dapat Dikembalikan.',
styles: PosStyles(align: PosAlign.center, bold: false));
bytes += generator.cut();
return bytes;
}
[@override](/user/override)
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
appBar: AppBar(
title: const Text('Bluetooth Thermal Printer Demo'),
),
body: Container(
padding: EdgeInsets.all(20),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text("搜索配对的蓝牙设备"),
TextButton(
onPressed: () {
this.getBluetooth();
},
child: Text("搜索"),
),
Container(
height: 200,
child: ListView.builder(
itemCount: availableBluetoothDevices.length > 0
? availableBluetoothDevices.length
: 0,
itemBuilder: (context, index) {
return ListTile(
onTap: () {
String select = availableBluetoothDevices[index];
List list = select.split("#");
// String name = list[0];
String mac = list[1];
this.setConnect(mac);
},
title: Text('${availableBluetoothDevices[index]}'),
subtitle: Text("点击连接"),
);
},
),
),
SizedBox(
height: 30,
),
TextButton(
onPressed: connected ? this.printGraphics : null,
child: Text("打印图形"),
),
TextButton(
onPressed: connected ? this.printTicket : null,
child: Text("打印票据"),
),
],
),
),
),
);
}
}
更多关于Flutter蓝牙打印机插件maswend_bt_printer的使用的实战教程也可以访问 https://www.itying.com/category-92-b0.html
更多关于Flutter蓝牙打印机插件maswend_bt_printer的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html
maswend_bt_printer
是一个用于在 Flutter 应用中连接和打印到蓝牙打印机的插件。以下是如何在 Flutter 项目中使用 maswend_bt_printer
插件的基本步骤:
1. 添加依赖
首先,你需要在 pubspec.yaml
文件中添加 maswend_bt_printer
依赖:
dependencies:
flutter:
sdk: flutter
maswend_bt_printer: ^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 代码中,导入 maswend_bt_printer
插件并初始化它:
import 'package:maswend_bt_printer/maswend_bt_printer.dart';
final MaswendBtPrinter printer = MaswendBtPrinter();
4. 搜索蓝牙设备
你可以使用 searchDevices
方法来搜索附近的蓝牙设备:
List<BluetoothDevice> devices = await printer.searchDevices();
5. 连接蓝牙打印机
选择一个设备并使用 connect
方法连接到它:
BluetoothDevice selectedDevice = devices[0];
bool isConnected = await printer.connect(selectedDevice);
if (isConnected) {
print("Connected to ${selectedDevice.name}");
} else {
print("Failed to connect");
}
6. 打印文本
连接成功后,你可以使用 printText
方法来打印文本:
String text = "Hello, World!";
await printer.printText(text);
7. 断开连接
打印完成后,记得断开连接:
await printer.disconnect();
完整示例
以下是一个完整的示例代码:
import 'package:flutter/material.dart';
import 'package:maswend_bt_printer/maswend_bt_printer.dart';
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
[@override](/user/override)
Widget build(BuildContext context) {
return MaterialApp(
home: BluetoothPrinterScreen(),
);
}
}
class BluetoothPrinterScreen extends StatefulWidget {
[@override](/user/override)
_BluetoothPrinterScreenState createState() => _BluetoothPrinterScreenState();
}
class _BluetoothPrinterScreenState extends State<BluetoothPrinterScreen> {
final MaswendBtPrinter printer = MaswendBtPrinter();
List<BluetoothDevice> devices = [];
BluetoothDevice? selectedDevice;
[@override](/user/override)
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Bluetooth Printer'),
),
body: Column(
children: [
ElevatedButton(
onPressed: _searchDevices,
child: Text('Search Devices'),
),
Expanded(
child: ListView.builder(
itemCount: devices.length,
itemBuilder: (context, index) {
return ListTile(
title: Text(devices[index].name),
subtitle: Text(devices[index].address),
onTap: () => _connectToDevice(devices[index]),
);
},
),
),
ElevatedButton(
onPressed: _printText,
child: Text('Print Text'),
),
],
),
);
}
Future<void> _searchDevices() async {
devices = await printer.searchDevices();
setState(() {});
}
Future<void> _connectToDevice(BluetoothDevice device) async {
bool isConnected = await printer.connect(device);
if (isConnected) {
setState(() {
selectedDevice = device;
});
print("Connected to ${device.name}");
} else {
print("Failed to connect");
}
}
Future<void> _printText() async {
if (selectedDevice != null) {
await printer.printText("Hello, World!");
} else {
print("No device connected");
}
}
}