Adicionar dependências ao seu pubspec.yaml
:
dependencies:
flutter:
sdk: flutter
blue_thermal_printer: ^1.1.0
Configurar permissões:
No Android, você precisa adicionar permissões ao arquivo AndroidManifest.xml
.
<uses-permission android:name=”android.permission.BLUETOOTH”/>
<uses-permission android:name=”android.permission.BLUETOOTH_ADMIN”/>
<uses-permission android:name=”android.permission.BLUETOOTH_SCAN”/>
<uses-permission android:name=”android.permission.BLUETOOTH_CONNECT”/>
Programa para interagir com a impressora:
import ‘package:flutter/material.dart’;
import ‘package:blue_thermal_printer/blue_thermal_printer.dart’;
void main() {
runApp(MyApp());
}
class MyApp extends StatefulWidget {
@override
_MyAppState createState() => _MyAppState();
}
class _MyAppState extends State {
BlueThermalPrinter bluetooth = BlueThermalPrinter.instance;
List _devices = [];
BluetoothDevice? _selectedDevice;
String _message = ”;
@override
void initState() {
super.initState();
initBluetooth();
}
Future initBluetooth() async {
bool? isConnected = await bluetooth.isConnected;
if (isConnected == null || !isConnected) {
_devices = await bluetooth.getBondedDevices();
setState(() {});
}
}
void _connect() {
if (_selectedDevice != null) {
bluetooth.connect(_selectedDevice!).catchError((error) {
setState(() {
_message = ‘Failed to connect: $error’;
});
});
}
}
void _disconnect() {
bluetooth.disconnect();
}
void _printSample() {
bluetooth.isConnected.then((isConnected) {
if (isConnected == true) {
bluetooth.printNewLine();
bluetooth.printCustom(“Hello World”, 3, 1);
bluetooth.printNewLine();
bluetooth.printQRcode(“Insert Your Own Text to Generate”, 200, 200, 1);
bluetooth.printNewLine();
bluetooth.printNewLine();
bluetooth.paperCut();
}
});
}
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
appBar: AppBar(
title: Text(‘Bluetooth Printer Example’),
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
DropdownButton(
items: _devices
.map((device) => DropdownMenuItem(
child: Text(device.name!),
value: device,
))
.toList(),
onChanged: (value) {
setState(() {
_selectedDevice = value;
});
},
hint: Text(‘Select a device’),
),
ElevatedButton(
onPressed: _connect,
child: Text(‘Connect’),
),
ElevatedButton(
onPressed: _disconnect,
child: Text(‘Disconnect’),
),
ElevatedButton(
onPressed: _printSample,
child: Text(‘Print Sample’),
),
Text(_message),
],
),
),
),
);
}
}