bluetooth_thermal_printer 0.0.1
bluetooth_thermal_printer: ^0.0.1 copied to clipboard
A simple Flutter plugin to connect to bluetooth printers
example/lib/main.dart
import 'dart:async';
import 'package:bluetooth_thermal_printer/bluetooth_thermal_printer.dart';
import 'package:esc_pos_utils/esc_pos_utils.dart';
import 'package:flutter/material.dart';
void main() {
runApp(MyApp());
}
class MyApp extends StatefulWidget {
@override
_MyAppState createState() => _MyAppState();
}
class _MyAppState extends State<MyApp> {
@override
void initState() {
super.initState();
}
bool connected = false;
List availableBluetoothDevices = new List();
Future<void> getBluetooth() async {
final List bluetooths = await BluetoothThermalPrinter.getBluetooths;
print("Print $bluetooths");
setState(() {
availableBluetoothDevices = bluetooths;
});
}
Future<void> setConnect(String mac) async {
final String result = await BluetoothThermalPrinter.connect(mac);
print("state conneected $result");
if (result == "true") {
setState(() {
connected = true;
});
}
}
Future<void> printTicket() async {
String isConnected = await BluetoothThermalPrinter.connectionStatus;
if (isConnected == "true") {
Ticket ticket = await getTicket();
final result = await BluetoothThermalPrinter.writeBytes(ticket.bytes);
print("Print $result");
} else {
//Hadnle Not Connected Senario
}
}
Future<Ticket> getTicket() async {
CapabilityProfile profile = await CapabilityProfile.load();
final Ticket ticket = Ticket(PaperSize.mm58, profile);
ticket.text('Test', styles: PosStyles(bold: true));
ticket.cut();
return ticket;
}
@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("Search Paired Bluetooth"),
OutlineButton(
onPressed: () {
this.getBluetooth();
},
child: Text("Search"),
),
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("Click to connect"),
);
},
),
),
SizedBox(
height: 30,
),
OutlineButton(
onPressed: connected ? this.printTicket : null,
child: Text("Print Ticket"),
),
],
),
),
),
);
}
}