posprinter_usb_android 1.1.0
posprinter_usb_android: ^1.1.0 copied to clipboard
Android USB host and network (TCP) transport for ESC/POS thermal receipt printers: discovery, permission handling and raw byte printing.
import 'dart:async';
import 'package:flutter/material.dart';
import 'package:posprinter_usb_android/posprinter_usb_android.dart';
void main() => runApp(const ExampleApp());
class ExampleApp extends StatelessWidget {
const ExampleApp({super.key});
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Thermal printer example',
debugShowCheckedModeBanner: false,
theme: ThemeData(
useMaterial3: true,
colorScheme: ColorScheme.fromSeed(seedColor: const Color(0xFF2563EB)),
),
home: const PrinterPage(),
);
}
}
class PrinterPage extends StatefulWidget {
const PrinterPage({super.key});
@override
State<PrinterPage> createState() => _PrinterPageState();
}
class _PrinterPageState extends State<PrinterPage> {
final PrinterManager _manager = PrinterManager.instance;
final List<PrinterDevice> _printers = <PrinterDevice>[];
StreamSubscription<PrinterDevice>? _discoverySubscription;
StreamSubscription<USBStatus>? _statusSubscription;
PrinterType _type = PrinterType.usb;
PrinterType? _connectedType;
PrinterDevice? _connectedPrinter;
USBStatus _status = USBStatus.none;
bool _busy = false;
@override
void initState() {
super.initState();
_statusSubscription = _manager.stateUSB.listen((USBStatus status) {
if (!mounted) return;
setState(() {
_status = status;
if (status == USBStatus.none) {
_connectedPrinter = null;
_connectedType = null;
}
});
});
// Deferred to the first frame: the plugin's discovery stream never
// completes, and `_scan` toggles state as soon as it starts.
WidgetsBinding.instance.addPostFrameCallback((Duration _) {
if (mounted) unawaited(_scan());
});
}
@override
void dispose() {
_discoverySubscription?.cancel();
_statusSubscription?.cancel();
super.dispose();
}
Future<void> _switchType(PrinterType type) async {
if (_busy || type == _type) return;
await _disconnect();
await _discoverySubscription?.cancel();
_discoverySubscription = null;
if (!mounted) return;
setState(() {
_type = type;
_printers.clear();
});
unawaited(_scan());
}
Future<void> _scan() async {
if (_busy) return;
setState(() {
_busy = true;
_printers.clear();
});
await _discoverySubscription?.cancel();
_discoverySubscription = _manager
.discovery(type: _type)
.listen(
(PrinterDevice device) {
if (!mounted) return;
setState(() => _printers.add(device));
},
onDone: () {
if (mounted) setState(() => _busy = false);
},
);
if (_type == PrinterType.usb) {
// The Android USB discovery stream has no completion event: give it a
// moment, then re-enable the UI.
await Future<void>.delayed(const Duration(seconds: 3));
if (mounted) setState(() => _busy = false);
}
}
Future<void> _connect(PrinterDevice device) async {
if (_busy) return;
final BasePrinterInput model;
if (_type == PrinterType.usb) {
model = UsbPrinterInput(
name: device.name,
vendorId: device.vendorId,
productId: device.productId,
);
} else {
model = TcpPrinterInput(
ipAddress: device.address ?? device.name.split(':').first,
);
}
await _connectWith(model, device);
}
Future<void> _connectManual() async {
final TextEditingController address = TextEditingController(
text: '192.168.1.50',
);
final TextEditingController port = TextEditingController(text: '9100');
final (String, int)? target = await showDialog<(String, int)>(
context: context,
builder: (BuildContext context) {
return AlertDialog(
title: const Text('Network printer'),
content: Column(
mainAxisSize: MainAxisSize.min,
children: <Widget>[
TextField(
controller: address,
keyboardType: TextInputType.url,
decoration: const InputDecoration(labelText: 'IP address'),
),
TextField(
controller: port,
keyboardType: TextInputType.number,
decoration: const InputDecoration(labelText: 'Port'),
),
],
),
actions: <Widget>[
TextButton(
onPressed: () => Navigator.of(context).pop(),
child: const Text('Cancel'),
),
FilledButton(
onPressed: () {
final int? value = int.tryParse(port.text);
final String host = address.text.trim();
if (host.isEmpty || value == null) return;
Navigator.of(context).pop((host, value));
},
child: const Text('Connect'),
),
],
);
},
);
address.dispose();
port.dispose();
if (target == null || !mounted) return;
final (String host, int value) = target;
final TcpPrinterInput model = TcpPrinterInput(ipAddress: host, port: value);
await _connectWith(
model,
PrinterDevice(name: '$host:$value', address: host),
);
}
Future<void> _connectWith(
BasePrinterInput model,
PrinterDevice device,
) async {
if (_busy) return;
setState(() => _busy = true);
final bool connected = await _manager.connect(type: _type, model: model);
if (!mounted) return;
setState(() {
_busy = false;
if (connected) {
_connectedPrinter = device;
_connectedType = _type;
}
});
_showMessage(
connected
? 'Connected to ${device.name}.'
: 'Could not connect to ${device.name}.',
);
}
Future<void> _printTest() async {
final PrinterType? type = _connectedType;
if (_busy || type == null) return;
setState(() => _busy = true);
final bool sent = await _manager.send(
type: type,
bytes: _testReceipt(type),
);
if (!mounted) return;
setState(() => _busy = false);
_showMessage(sent ? 'Test receipt sent.' : 'Print failed.');
}
Future<void> _disconnect() async {
final PrinterType? type = _connectedType;
if (type == null) return;
setState(() => _busy = true);
await _manager.disconnect(type: type);
if (!mounted) return;
setState(() {
_busy = false;
_connectedPrinter = null;
_connectedType = null;
});
}
void _showMessage(String message) {
if (!mounted) return;
ScaffoldMessenger.of(context)
..hideCurrentSnackBar()
..showSnackBar(SnackBar(content: Text(message)));
}
/// Minimal ESC/POS test page: reset, centre, text, feed, cut.
List<int> _testReceipt(PrinterType type) {
final List<int> bytes = <int>[
0x1B, 0x40, // reset
0x1B, 0x61, 0x01, // centre
];
bytes.addAll('${type.name.toUpperCase()} PRINT TEST\n'.codeUnits);
bytes.addAll(<int>[0x1B, 0x61, 0x00]); // left
bytes.addAll(
'Printer: ${_connectedPrinter?.name ?? 'unknown'}\n'.codeUnits,
);
bytes.addAll('Printed: ${DateTime.now()}\n'.codeUnits);
bytes.addAll(<int>[0x0A, 0x0A, 0x0A]);
bytes.addAll(<int>[0x1D, 0x56, 0x00]); // cut
return bytes;
}
bool _isConnected(PrinterDevice device) {
final PrinterDevice? current = _connectedPrinter;
if (current == null || _connectedType != _type) return false;
if (current.vendorId != null && device.vendorId != null) {
return current.vendorId == device.vendorId &&
current.productId == device.productId;
}
return current.name == device.name;
}
String _subtitle(PrinterDevice device) {
if (_type == PrinterType.network) {
return device.address == null
? 'Network printer'
: '${device.address}:9100';
}
return device.vendorId == null
? 'USB printer'
: 'VID ${device.vendorId} • PID ${device.productId}';
}
@override
Widget build(BuildContext context) {
final bool isNetwork = _type == PrinterType.network;
return Scaffold(
appBar: AppBar(title: const Text('Thermal printer')),
body: SafeArea(
child: Column(
children: <Widget>[
Padding(
padding: const EdgeInsets.fromLTRB(12, 12, 12, 8),
child: SegmentedButton<PrinterType>(
segments: const <ButtonSegment<PrinterType>>[
ButtonSegment<PrinterType>(
value: PrinterType.usb,
icon: Icon(Icons.usb_rounded),
label: Text('USB'),
),
ButtonSegment<PrinterType>(
value: PrinterType.network,
icon: Icon(Icons.router_rounded),
label: Text('Network'),
),
],
selected: <PrinterType>{_type},
onSelectionChanged: _busy
? null
: (Set<PrinterType> selection) =>
unawaited(_switchType(selection.first)),
),
),
Padding(
padding: const EdgeInsets.symmetric(horizontal: 12),
child: Row(
children: <Widget>[
Expanded(
child: FilledButton.icon(
onPressed: _busy ? null : _scan,
icon: Icon(
isNetwork ? Icons.wifi_find_rounded : Icons.usb_rounded,
),
label: Text(_busy ? 'Working…' : 'Scan for printers'),
),
),
if (isNetwork) ...<Widget>[
const SizedBox(width: 8),
OutlinedButton.icon(
onPressed: _busy ? null : _connectManual,
icon: const Icon(Icons.add_rounded),
label: const Text('Add IP'),
),
],
],
),
),
if (!isNetwork)
Padding(
padding: const EdgeInsets.fromLTRB(12, 8, 12, 0),
child: Align(
alignment: Alignment.centerLeft,
child: Text(
'USB state: ${_status.name}',
style: Theme.of(context).textTheme.bodySmall,
),
),
),
Expanded(
child: _printers.isEmpty
? Center(
child: Padding(
padding: const EdgeInsets.all(24),
child: Text(
isNetwork
? 'Scan the local network for printers listening '
'on port 9100, or add one by IP address.'
: 'Attach a USB receipt printer, then tap Scan. '
'Android will ask for permission the first '
'time you connect.',
textAlign: TextAlign.center,
),
),
)
: ListView.builder(
itemCount: _printers.length,
itemBuilder: (BuildContext context, int index) {
final PrinterDevice device = _printers[index];
final bool connected = _isConnected(device);
return ListTile(
leading: Icon(
connected
? Icons.print_rounded
: isNetwork
? Icons.router_rounded
: Icons.usb_rounded,
),
title: Text(device.name),
subtitle: Text(_subtitle(device)),
trailing: connected
? const Text('Connected')
: const Icon(Icons.chevron_right_rounded),
onTap: _busy ? null : () => _connect(device),
);
},
),
),
if (_connectedPrinter != null)
Padding(
padding: const EdgeInsets.all(12),
child: Row(
children: <Widget>[
Expanded(
child: FilledButton.icon(
onPressed: _busy ? null : _printTest,
icon: const Icon(Icons.print_rounded),
label: const Text('Test print'),
),
),
const SizedBox(width: 8),
Expanded(
child: OutlinedButton.icon(
onPressed: _busy ? null : _disconnect,
icon: const Icon(Icons.link_off_rounded),
label: const Text('Disconnect'),
),
),
],
),
),
],
),
),
);
}
}