flutter plugin for zebra multiplatform sdk

main.dart 10KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339
  1. import 'dart:developer';
  2. import 'dart:math';
  3. import 'package:flutter/material.dart';
  4. import 'dart:async';
  5. import 'package:flutter/services.dart';
  6. import 'package:flutter_zsdk/flutter_zsdk.dart';
  7. import 'package:flutter_zsdk/src/models/flutter_zsdk_exception.dart';
  8. import 'package:flutter_zsdk/src/models/error_code.dart';
  9. import 'package:flutter_zsdk_example/models/bluetooth_printer.dart';
  10. void main() {
  11. runApp(const MaterialApp(home: MyApp()));
  12. }
  13. class MyApp extends StatefulWidget {
  14. const MyApp({super.key});
  15. @override
  16. State<MyApp> createState() => _MyAppState();
  17. }
  18. class _MyAppState extends State<MyApp> {
  19. final _formKey = GlobalKey<FormState>();
  20. bool _isDiscovering = false;
  21. List<BluetoothPrinter> _discoveredBluetoothPrinters = [];
  22. String? _connectedPrinter;
  23. final _flutterZsdkPlugin = FlutterZsdk();
  24. String? _selectedBluetoothPrinterMacAddress;
  25. bool _disconnecting = false;
  26. TextEditingController _zplDataController = TextEditingController();
  27. @override
  28. void initState() {
  29. super.initState();
  30. // initPlatformState();
  31. }
  32. // Platform messages are asynchronous, so we initialize in an async method.
  33. // Future<void> initPlatformState() async {
  34. // String platformVersion;
  35. // // Platform messages may fail, so we use a try/catch PlatformException.
  36. // // We also handle the message potentially returning null.
  37. // try {
  38. // platformVersion =
  39. // await _flutterZsdkPlugin.getPlatformVersion() ?? 'Unknown platform version';
  40. // } on PlatformException {
  41. // platformVersion = 'Failed to get platform version.';
  42. // }
  43. // // If the widget was removed from the tree while the asynchronous platform
  44. // // message was in flight, we want to discard the reply rather than calling
  45. // // setState to update our non-existent appearance.
  46. // if (!mounted) return;
  47. // setState(() {
  48. // _platformVersion = platformVersion;
  49. // });
  50. // }
  51. StreamSubscription? _bluetoothPrinterSubscription;
  52. void showSnackBar(String message) {
  53. ScaffoldMessenger.of(context).showSnackBar(
  54. SnackBar(content: Text(message))
  55. );
  56. }
  57. Future<void> discoverBluetoothDevices() async {
  58. try {
  59. Stream<dynamic> stream = await _flutterZsdkPlugin.findBluetoothPrinters();
  60. _bluetoothPrinterSubscription = stream.listen((event) {
  61. print(event);
  62. if (event == 'SOS') {
  63. _isDiscovering = true;
  64. }
  65. if (event is List) {
  66. _discoveredBluetoothPrinters.clear();
  67. for (var printer in event) {
  68. BluetoothPrinter bluetoothPrinter = BluetoothPrinter.fromMap(printer);
  69. _discoveredBluetoothPrinters.add(bluetoothPrinter);
  70. }
  71. }
  72. if (event == 'EOS') {
  73. _isDiscovering = false;
  74. showSnackBar('Bluetooth discovery finished, found ${_discoveredBluetoothPrinters.length} printers');
  75. _bluetoothPrinterSubscription?.cancel();
  76. }
  77. setState(() {});
  78. });
  79. } on PlatformException catch (e) {
  80. inspect(e);
  81. showSnackBar(e.message.toString());
  82. } on FlutterZsdkException catch (e) {
  83. inspect(e);
  84. showSnackBar(e.message);
  85. if (e.code == ErrorCode.locationServiceDisabled) {
  86. showDialog(
  87. context: context,
  88. builder: (context) => AlertDialog(
  89. title: Text('Location service disabled'),
  90. content: Text(
  91. 'This app require location service to scan bluetooth printers, please turn on location service on your device'
  92. ),
  93. ),
  94. );
  95. }
  96. } catch (e) {
  97. inspect(e);
  98. showSnackBar('Unexpected error while discovering bluetooth printers');
  99. }
  100. }
  101. Future<void> openConnection() async {
  102. print('invoked openConnection from dart');
  103. try {
  104. await _flutterZsdkPlugin.openConnection(_selectedBluetoothPrinterMacAddress ?? '');
  105. _connectedPrinter = _selectedBluetoothPrinterMacAddress ?? 'Unknown printer';
  106. print('Connection opened successfully from dart');
  107. } on FlutterZsdkException catch (e) {
  108. inspect(e);
  109. showSnackBar(e.message);
  110. } catch (e) {
  111. inspect(e);
  112. showSnackBar('Unexpected error while connecting to bluetooth printers');
  113. }
  114. setState(() {});
  115. }
  116. Future<void> closeConnection() async {
  117. print('invoked closeConnection from dart');
  118. try {
  119. setState(() {
  120. _disconnecting = true;
  121. });
  122. await _flutterZsdkPlugin.closeConnection();
  123. _connectedPrinter = null;
  124. _disconnecting = false;
  125. print('Connection closed successfully from dart');
  126. } on FlutterZsdkException catch (e) {
  127. inspect(e);
  128. showSnackBar(e.message);
  129. } catch (e) {
  130. inspect(e);
  131. showSnackBar('Unexpected error while disconnecting bluetooth printers');
  132. }
  133. setState(() {});
  134. }
  135. Future<void> printZplOverBluetooth() async {
  136. if(!_formKey.currentState!.validate()) {
  137. return;
  138. }
  139. print('invoked printZplOverBluetooth from dart');
  140. try {
  141. await _flutterZsdkPlugin.printZplOverBluetooth(_zplDataController.text);
  142. print('printZplOverBluetooth successfully from dart');
  143. } on FlutterZsdkException catch (e) {
  144. inspect(e);
  145. showSnackBar(e.message);
  146. } catch (e) {
  147. inspect(e);
  148. showSnackBar('Unexpected error when send data to printers');
  149. }
  150. setState(() {});
  151. }
  152. Future<void> checkConnectionStatus() async {
  153. print('invoked checkConnectionStatus from dart');
  154. try{
  155. bool isConnected = await _flutterZsdkPlugin.isConnected();
  156. print('isConnected from dart: $isConnected');
  157. } on FlutterZsdkException catch (e) {
  158. inspect(e);
  159. showSnackBar(e.message.toString());
  160. } catch (e) {
  161. inspect(e);
  162. showSnackBar('Unexpected error while checking connection status');
  163. }
  164. }
  165. Future<void> calibrate() async {
  166. print('invoked calibrate from dart');
  167. try{
  168. await _flutterZsdkPlugin.calibrate();
  169. } on FlutterZsdkException catch (e) {
  170. inspect(e);
  171. showSnackBar(e.message.toString());
  172. } catch (e) {
  173. inspect(e);
  174. showSnackBar('Unexpected error while calibrating printer');
  175. }
  176. }
  177. Future<void> debugTest() async {
  178. print('invoked debugTest from dart');
  179. try{
  180. await _flutterZsdkPlugin.debugTest();
  181. } on FlutterZsdkException catch (e) {
  182. inspect(e);
  183. showSnackBar(e.message.toString());
  184. } catch (e) {
  185. inspect(e);
  186. showSnackBar('Unexpected error while checking connection status');
  187. }
  188. }
  189. @override
  190. Widget build(BuildContext context) {
  191. return Scaffold(
  192. appBar: AppBar(
  193. title: const Text('Plugin example app'),
  194. ),
  195. body: Form(
  196. key: _formKey,
  197. child: Center(
  198. child: SingleChildScrollView(
  199. child: Column(
  200. crossAxisAlignment: CrossAxisAlignment.center,
  201. mainAxisAlignment: MainAxisAlignment.center,
  202. children: [
  203. Text('Connected printer: ${_connectedPrinter ?? "Unknown printer"}\n'),
  204. Text('Selected printer Mac Address: $_selectedBluetoothPrinterMacAddress\n'),
  205. SizedBox(height: 20),
  206. ElevatedButton(
  207. child: Text('Connect to $_selectedBluetoothPrinterMacAddress'),
  208. onPressed: _selectedBluetoothPrinterMacAddress == null ? null : openConnection,
  209. ),
  210. SizedBox(height: 20),
  211. ElevatedButton(
  212. child: Text(_disconnecting ? 'Disconnecting...' : 'Disconnect from $_connectedPrinter'),
  213. onPressed: _connectedPrinter == null || _disconnecting ? null : closeConnection,
  214. ),
  215. SizedBox(height: 20),
  216. // debug button
  217. ElevatedButton(
  218. child: Text('Debug'),
  219. onPressed: debugTest
  220. ),
  221. SizedBox(height: 20),
  222. // calibrate button
  223. ElevatedButton(
  224. child: Text('Calibrate'),
  225. onPressed: _connectedPrinter == null || _disconnecting ? null : calibrate
  226. ),
  227. SizedBox(height: 20),
  228. TextFormField(
  229. controller: _zplDataController,
  230. decoration: InputDecoration(
  231. hintText: 'Enter ZPL data here'
  232. ),
  233. validator: (value) {
  234. if (value == null || value.isEmpty) {
  235. return 'Please enter some text';
  236. }
  237. return null;
  238. },
  239. ),
  240. ElevatedButton(
  241. child: Text('Print zpl over bluetooth'),
  242. onPressed: _connectedPrinter == null ? null : printZplOverBluetooth,
  243. ),
  244. SizedBox(height: 20),
  245. ElevatedButton(
  246. child: Text('Check connection status'),
  247. onPressed: checkConnectionStatus,
  248. ),
  249. SizedBox(height: 20),
  250. ElevatedButton(
  251. child: Text(_isDiscovering ? 'Discovering bluetooth printers...' : 'Discover nearby bluetooth printers'),
  252. onPressed: _isDiscovering ? null : () async {
  253. discoverBluetoothDevices();
  254. },
  255. ),
  256. SizedBox(height: 20),
  257. for (var printer in _discoveredBluetoothPrinters) ... [
  258. InkWell(
  259. onTap: () {
  260. _selectedBluetoothPrinterMacAddress = printer.macAddress;
  261. setState(() {});
  262. },
  263. child: Column(
  264. mainAxisSize: MainAxisSize.min,
  265. children: [
  266. Text(printer.friendlyName),
  267. Text(printer.macAddress),
  268. SizedBox(height: 10)
  269. ],
  270. ),
  271. )
  272. ]
  273. ]
  274. ),
  275. ),
  276. ),
  277. ),
  278. );
  279. }
  280. }