smart_bluetooth_pos_printer 1.0.0
smart_bluetooth_pos_printer: ^1.0.0 copied to clipboard
A flutter plugin that prints esc commands to printers in different platforms such as android, ios, windows and different interfaces Bluetooth and BLE
example/lib/main.dart
import 'dart:async';
import 'dart:developer';
import 'dart:io';
import 'package:esc_pos_utils/esc_pos_utils.dart';
import 'package:flutter/material.dart';
import 'package:smart_bluetooth_pos_printer/smart_bluetooth_pos_printer.dart';
void main() {
runApp(const MyApp());
}
class MyApp extends StatefulWidget {
const MyApp({Key? key}) : super(key: key);
@override
State<MyApp> createState() => _MyAppState();
}
class _MyAppState extends State<MyApp> {
var _isBle = false;
var _reconnect = false;
var _isConnected = false;
var printerManager = PrinterManager.instance;
var devices = <BluetoothPrinter>[];
StreamSubscription<PrinterDevice>? _subscription;
StreamSubscription<BTStatus>? _subscriptionBtStatus;
BTStatus _currentStatus = BTStatus.none;
// _currentUsbStatus is only supports on Android
// ignore: unused_field
List<int>? pendingTask;
BluetoothPrinter? selectedPrinter;
@override
void initState() {
super.initState();
_scan();
// subscription to listen change status of bluetooth connection
_subscriptionBtStatus =
PrinterManager.instance.stateBluetooth.listen((status) {
log(' ----------------- status bt $status ------------------ ');
_currentStatus = status;
if (status == BTStatus.connected) {
setState(() {
_isConnected = true;
});
}
if (status == BTStatus.none) {
setState(() {
_isConnected = false;
});
}
if (status == BTStatus.connected && pendingTask != null) {
if (Platform.isAndroid) {
Future.delayed(const Duration(milliseconds: 1000), () {
PrinterManager.instance.send(bytes: pendingTask!);
pendingTask = null;
});
} else if (Platform.isIOS) {
PrinterManager.instance.send(bytes: pendingTask!);
pendingTask = null;
}
}
});
}
@override
void dispose() {
_subscription?.cancel();
_subscriptionBtStatus?.cancel();
super.dispose();
}
// method to scan devices according PrinterType
void _scan() {
devices.clear();
_subscription = printerManager.discovery(isBle: _isBle).listen((device) {
devices.add(BluetoothPrinter(
deviceName: device.name,
address: device.address,
isBle: _isBle,
));
setState(() {});
});
}
void selectDevice(BluetoothPrinter device) async {
if (selectedPrinter != null) {
if (device.address != selectedPrinter!.address) {
await PrinterManager.instance.disconnect();
}
}
selectedPrinter = device;
setState(() {});
}
Future _printReceiveTest() async {
List<int> bytes = [];
// Xprinter XP-N160I
final profile = await CapabilityProfile.load(name: 'XP-N160I');
// PaperSize.mm80 or PaperSize.mm58
final generator = Generator(PaperSize.mm80, profile);
bytes += generator.setGlobalCodeTable('CP1252');
bytes += generator.text('Test Print',
styles: const PosStyles(align: PosAlign.center));
bytes += generator.text('Product 1');
bytes += generator.text('Product 2');
_printEscPos(bytes, generator);
}
/// print ticket
void _printEscPos(List<int> bytes, Generator generator) async {
if (selectedPrinter == null) return;
var bluetoothPrinter = selectedPrinter!;
bytes += generator.cut();
await printerManager.connect(
model: BluetoothPrinterInput(
name: bluetoothPrinter.deviceName,
address: bluetoothPrinter.address!,
isBle: bluetoothPrinter.isBle ?? false,
autoConnect: _reconnect));
pendingTask = null;
if (Platform.isAndroid) pendingTask = bytes;
if (Platform.isAndroid) {
if (_currentStatus == BTStatus.connected) {
printerManager.send(bytes: bytes);
pendingTask = null;
}
} else {
printerManager.send(bytes: bytes);
}
}
// conectar dispositivo
_connectDevice() async {
_isConnected = false;
if (selectedPrinter == null) return;
await printerManager.connect(
model: BluetoothPrinterInput(
name: selectedPrinter!.deviceName,
address: selectedPrinter!.address!,
isBle: selectedPrinter!.isBle ?? false,
autoConnect: _reconnect));
setState(() {});
}
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
appBar: AppBar(
title: const Text('Flutter Pos Plugin Platform example app'),
),
body: Center(
child: Container(
height: double.infinity,
constraints: const BoxConstraints(maxWidth: 400),
child: SingleChildScrollView(
padding: EdgeInsets.zero,
child: Column(
children: [
Padding(
padding: const EdgeInsets.all(8.0),
child: Row(
children: [
Expanded(
child: ElevatedButton(
onPressed: selectedPrinter == null || _isConnected
? null
: () {
_connectDevice();
},
child: const Text("Connect",
textAlign: TextAlign.center),
),
),
const SizedBox(width: 8),
Expanded(
child: ElevatedButton(
onPressed: selectedPrinter == null || !_isConnected
? null
: () {
if (selectedPrinter != null) {
printerManager.disconnect();
setState(() {
_isConnected = false;
});
}
},
child: const Text("Disconnect",
textAlign: TextAlign.center),
),
),
],
),
),
Visibility(
visible: Platform.isAndroid,
child: SwitchListTile.adaptive(
contentPadding:
const EdgeInsets.only(bottom: 20.0, left: 20),
title: const Text(
"This device supports ble (low energy)",
textAlign: TextAlign.start,
style: TextStyle(fontSize: 19.0),
),
value: _isBle,
onChanged: (bool? value) {
setState(() {
_isBle = value ?? false;
_isConnected = false;
selectedPrinter = null;
_scan();
});
},
),
),
Visibility(
visible: Platform.isAndroid,
child: SwitchListTile.adaptive(
contentPadding:
const EdgeInsets.only(bottom: 20.0, left: 20),
title: const Text(
"reconnect",
textAlign: TextAlign.start,
style: TextStyle(fontSize: 19.0),
),
value: _reconnect,
onChanged: (bool? value) {
setState(() {
_reconnect = value ?? false;
});
},
),
),
Column(
children: devices
.map(
(device) => ListTile(
title: Text('${device.deviceName}'),
onTap: () {
// do something
selectDevice(device);
},
leading: selectedPrinter != null &&
((device.address != null &&
selectedPrinter!.address ==
device.address))
? const Icon(
Icons.check,
color: Colors.green,
)
: null,
trailing: OutlinedButton(
onPressed: selectedPrinter == null ||
device.deviceName !=
selectedPrinter?.deviceName
? null
: () async {
_printReceiveTest();
},
child: const Padding(
padding: EdgeInsets.symmetric(
vertical: 2, horizontal: 20),
child: Text("Print test ticket",
textAlign: TextAlign.center),
),
),
),
)
.toList()),
],
),
),
),
),
),
);
}
}
class BluetoothPrinter {
int? id;
String? deviceName;
String? address;
bool? isBle;
bool? state;
BluetoothPrinter(
{this.deviceName, this.address, this.state, this.isBle = false});
}