Flutter标签打印插件idata_label_printer的使用
Flutter标签打印插件idata_label_printer的使用
A new Flutter plugin for connecting to iData热敏/标签打印机通过蓝牙(仅限Android),此插件仍在开发中。
平台支持
Android | iOS | MacOS | Web | Linux | Windows |
---|---|---|---|---|---|
✔️ | X | X | X | X | X |
开始使用
1. 添加依赖
在你的包的pubspec.yaml
文件中添加以下依赖:
dependencies:
idata_label_printer: ^any
2. 安装依赖
你可以通过命令行安装包:
通过 Flutter:
flutter packages get
或者,你的编辑器可能支持flutter packages get
。查看编辑器文档了解更多详情。
3. 导入库
现在你可以在Dart代码中使用:
import 'package:idata_label_printer/idata_label_printer.dart';
示例代码
详细的演示请参阅example文件夹。
注意:确保将项目升级到编译SDK版本31或更高版本。
如果你喜欢我的内容,请考虑请我喝杯咖啡。感谢你的支持!
示例代码详解
以下是完整的示例代码,展示了如何使用idata_label_printer
插件进行标签打印。
// 忽略对文件的警告:避免打印,使用BuildContext时异步
import 'package:flutter/material.dart';
import 'dart:async';
import 'package:flutter/services.dart';
import 'package:idata_label_printer/idata_label_printer.dart';
import 'package:idata_label_printer_example/printtest.dart';
void main() {
runApp(const MyAppWrapper());
}
class MyAppWrapper extends StatelessWidget {
const MyAppWrapper({super.key});
[@override](/user/override)
Widget build(BuildContext context) {
return const MaterialApp(
debugShowCheckedModeBanner: false,
home: MyApp(),
);
}
}
class MyApp extends StatefulWidget {
const MyApp({super.key});
[@override](/user/override)
State<MyApp> createState() => _MyAppState();
}
class _MyAppState extends State<MyApp> {
IdataLabelPrinter bluetooth = IdataLabelPrinter.instance;
List<BluetoothDevice> devices = [];
BluetoothDevice? device;
bool connected = false;
String tips = "";
PrintTest printTest = PrintTest();
final GlobalKey<State> keyLoader = GlobalKey<State>();
[@override](/user/override)
void initState() {
super.initState();
initPlatformState();
}
void setStateIfMounted(f) {
if (mounted) setState(f);
}
// 平台消息是异步的,所以我们初始化在一个异步方法中。
Future<void> initPlatformState() async {
bool? isConnected = await bluetooth.isConnected;
List<BluetoothDevice> devicesList = [];
try {
devicesList = await bluetooth.getBluetoothDevices();
} on PlatformException catch (e) {
Future.delayed(Duration.zero, () {
showAlertDialog(context, "错误!", e.message.toString());
});
}
bluetooth.onStateChanged().listen((state) {
switch (state) {
case (IdataLabelPrinter.STATE_CONNECTED || IdataLabelPrinter.CONNECTED):
setStateIfMounted(() {
connected = true;
tips = "蓝牙设备状态:已连接";
});
break;
case IdataLabelPrinter.STATE_DISCONNECTED:
setStateIfMounted(() {
connected = false;
tips = "蓝牙设备状态:已断开连接";
});
break;
case IdataLabelPrinter.STATE_TURNING_OFF:
setStateIfMounted(() {
connected = false;
tips = "蓝牙设备状态:蓝牙关闭中";
});
break;
case IdataLabelPrinter.STATE_OFF:
setStateIfMounted(() {
connected = false;
tips = "蓝牙设备状态:蓝牙已关闭";
});
break;
case IdataLabelPrinter.STATE_ON:
setStateIfMounted(() {
connected = false;
tips = "蓝牙设备状态:蓝牙已开启";
});
break;
case IdataLabelPrinter.STATE_TURNING_ON:
setStateIfMounted(() {
connected = false;
tips = "蓝牙设备状态:蓝牙开启中";
});
break;
case IdataLabelPrinter.ERROR:
setStateIfMounted(() {
connected = false;
tips = "蓝牙设备状态:错误";
});
break;
default:
setStateIfMounted(() {
connected = false;
tips = "蓝牙设备状态:$state";
});
break;
}
});
if (!mounted) return;
setState(() {
devices = devicesList;
});
if (isConnected == true) {
setState(() {
connected = true;
});
}
}
Future<void> connect(BluetoothDevice device) async {
try {
Dialogs.showLoadingDialog(context, keyLoader);
if (!connected) {
await bluetooth.connect(device).then((_) =>
Navigator.of(keyLoader.currentContext!, rootNavigator: true).pop());
}
} on PlatformException catch (e) {
Navigator.of(keyLoader.currentContext!, rootNavigator: true).pop();
showAlertDialog(context, "错误!", e.message.toString());
}
}
Future<void> disconnect() async {
try {
Dialogs.showLoadingDialog(context, keyLoader);
await bluetooth.disconnect();
Navigator.of(keyLoader.currentContext!, rootNavigator: true).pop();
} on PlatformException catch (e) {
Navigator.of(keyLoader.currentContext!, rootNavigator: true).pop();
showAlertDialog(context, "错误!", e.message.toString());
}
}
void showAlertDialog(BuildContext context, String title, String message) {
showDialog(
context: context,
builder: (BuildContext context) {
return AlertDialog(
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(8.0),
),
backgroundColor: Colors.white,
title: Text(
title.toUpperCase(),
style: const TextStyle(
fontSize: 14.0,
fontWeight: FontWeight.w700,
),
),
content: Text(message, style: const TextStyle(fontSize: 14.0)),
actions: <Widget>[
TextButton(
style: TextButton.styleFrom(
backgroundColor: Colors.grey,
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(8.0))),
child: const Text(
'确定',
style: TextStyle(fontSize: 14.0, color: Colors.white),
),
onPressed: () {
Navigator.of(context).pop();
},
),
],
);
},
);
}
[@override](/user/override)
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text('iData标签打印机'),
),
body: Padding(
padding: const EdgeInsets.all(16.0),
child: Column(
children: [
Expanded(
child: SingleChildScrollView(
child: Column(
children: [
Row(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Padding(
padding: const EdgeInsets.all(10.0),
child: Text(
tips,
style: const TextStyle(fontSize: 14.0),
),
),
],
),
const Divider(),
SizedBox(
height: MediaQuery.of(context).size.height * 0.63,
child: ListView.builder(
physics: const BouncingScrollPhysics(),
itemCount: devices.length,
itemBuilder: (context, index) {
return listTile(devices[index]);
},
),
),
const Divider(),
Row(
mainAxisAlignment: MainAxisAlignment.center,
children: [
OutlinedButton(
onPressed: connected ? () => printTest.slip() : () {},
style: OutlinedButton.styleFrom(
foregroundColor:
connected ? Colors.green : Colors.black12,
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(8.0),
),
side: BorderSide(
width: 1.0,
color: connected ? Colors.green : Colors.black12,
),
),
child: const Text("打印测试"),
),
],
),
],
),
),
),
],
),
),
);
}
listTile(BluetoothDevice d) {
return ListTile(
title: Row(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
const Icon(Icons.print_rounded, color: Colors.black, size: 20.0),
const SizedBox(width: 4.0),
Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
d.name ?? '',
style: const TextStyle(
fontSize: 14.0,
fontWeight: FontWeight.w700,
color: Colors.black,
),
),
Text(
d.address ?? '',
style: const TextStyle(
fontSize: 12.0,
fontWeight: FontWeight.w600,
color: Color(0xFF999999),
),
),
],
),
],
),
onTap: () async {
setState(() {
device = d;
});
},
trailing: OutlinedButton(
onPressed: connected
? disconnect
: () {
connect(d);
},
style: OutlinedButton.styleFrom(
foregroundColor: connected ? Colors.red : Colors.green,
padding: const EdgeInsets.all(6.0),
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(8.0),
),
side: BorderSide(
width: 1.0,
color: connected ? Colors.red : Colors.green,
),
),
child: Text(
connected ? "断开连接" : "连接",
),
),
);
}
}
class Dialogs {
static Future<void> showLoadingDialog(
BuildContext context, GlobalKey key) async {
return showDialog<void>(
context: context,
barrierDismissible: false,
builder: (BuildContext context) {
return PopScope(
canPop: false,
child: SimpleDialog(
key: key,
backgroundColor: Colors.white,
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(8.0),
),
children: const <Widget>[
Center(
child: Row(
crossAxisAlignment: CrossAxisAlignment.center,
mainAxisAlignment: MainAxisAlignment.center,
children: [
CircularProgressIndicator(
color: Colors.grey,
strokeWidth: 4.0,
),
SizedBox(width: 8.0),
Text(
"请等待...",
style: TextStyle(
fontSize: 14.0,
color: Colors.black,
),
),
],
),
),
],
),
);
},
);
}
}
更多关于Flutter标签打印插件idata_label_printer的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html
idata_label_printer
是一个用于 Flutter 的插件,专门用于与 iData 标签打印机进行通信和打印。这个插件可以帮助你在 Flutter 应用中实现标签打印功能。以下是使用 idata_label_printer
插件的基本步骤:
1. 添加依赖
首先,你需要在 pubspec.yaml
文件中添加 idata_label_printer
插件的依赖:
dependencies:
flutter:
sdk: flutter
idata_label_printer: ^1.0.0 # 请使用最新版本
然后运行 flutter pub get
来获取依赖。
2. 导入插件
在你的 Dart 文件中导入 idata_label_printer
插件:
import 'package:idata_label_printer/idata_label_printer.dart';
3. 初始化打印机
在使用打印机之前,你需要先初始化打印机。通常,你可以通过蓝牙或 Wi-Fi 连接打印机。
final IDataLabelPrinter printer = IDataLabelPrinter();
Future<void> initPrinter() async {
bool isConnected = await printer.connect();
if (isConnected) {
print("Printer connected successfully.");
} else {
print("Failed to connect to the printer.");
}
}
4. 打印标签
连接成功后,你可以使用 printer.printLabel
方法来打印标签。你需要传入打印内容和打印参数。
Future<void> printLabel() async {
String content = """
^XA
^FO50,50^A0N,50,50^FDHello, World!^FS
^XZ
""";
bool isPrinted = await printer.printLabel(content);
if (isPrinted) {
print("Label printed successfully.");
} else {
print("Failed to print the label.");
}
}
5. 断开连接
打印完成后,你可以断开与打印机的连接:
Future<void> disconnectPrinter() async {
bool isDisconnected = await printer.disconnect();
if (isDisconnected) {
print("Printer disconnected successfully.");
} else {
print("Failed to disconnect the printer.");
}
}
6. 处理错误
在实际使用中,可能会遇到各种错误,比如连接失败、打印失败等。你可以通过捕获异常来处理这些错误。
Future<void> printLabelWithErrorHandling() async {
try {
await initPrinter();
await printLabel();
await disconnectPrinter();
} catch (e) {
print("An error occurred: $e");
}
}
7. 其他功能
idata_label_printer
插件可能还提供其他功能,比如获取打印机状态、设置打印参数等。你可以查阅插件的文档或源代码以了解更多详细信息。
8. 调试和测试
在实际开发中,建议在真实设备上进行调试和测试,以确保打印功能正常工作。
示例代码
以下是一个完整的示例代码:
import 'package:flutter/material.dart';
import 'package:idata_label_printer/idata_label_printer.dart';
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
[@override](/user/override)
Widget build(BuildContext context) {
return MaterialApp(
home: PrinterScreen(),
);
}
}
class PrinterScreen extends StatelessWidget {
final IDataLabelPrinter printer = IDataLabelPrinter();
Future<void> initPrinter() async {
bool isConnected = await printer.connect();
if (isConnected) {
print("Printer connected successfully.");
} else {
print("Failed to connect to the printer.");
}
}
Future<void> printLabel() async {
String content = """
^XA
^FO50,50^A0N,50,50^FDHello, World!^FS
^XZ
""";
bool isPrinted = await printer.printLabel(content);
if (isPrinted) {
print("Label printed successfully.");
} else {
print("Failed to print the label.");
}
}
Future<void> disconnectPrinter() async {
bool isDisconnected = await printer.disconnect();
if (isDisconnected) {
print("Printer disconnected successfully.");
} else {
print("Failed to disconnect the printer.");
}
}
Future<void> printLabelWithErrorHandling() async {
try {
await initPrinter();
await printLabel();
await disconnectPrinter();
} catch (e) {
print("An error occurred: $e");
}
}
[@override](/user/override)
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('iData Label Printer Example'),
),
body: Center(
child: ElevatedButton(
onPressed: printLabelWithErrorHandling,
child: Text('Print Label'),
),
),
);
}
}