flutter_usb_printer 0.1.0+1 flutter_usb_printer: ^0.1.0+1 copied to clipboard
This plugin will allow develop send data and work with usb printer on android
import 'dart:convert';
import 'dart:typed_data';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_usb_printer/flutter_usb_printer.dart';
void main() => runApp(new MyApp());
class MyApp extends StatefulWidget {
@override
_MyAppState createState() => new _MyAppState();
}
class _MyAppState extends State<MyApp> {
List<Map<String, dynamic>> devices = [];
FlutterUsbPrinter flutterUsbPrinter = FlutterUsbPrinter();
bool connected = false;
@override
initState() {
super.initState();
_getDevicelist();
}
_getDevicelist() async {
List<Map<String, dynamic>> results = [];
results = await FlutterUsbPrinter.getUSBDeviceList();
print(" length: ${results.length}");
setState(() {
devices = results;
});
}
_connect(int vendorId, int productId) async {
bool? returned = false;
try {
returned = await flutterUsbPrinter.connect(vendorId, productId);
} on PlatformException {
//response = 'Failed to get platform version.';
}
if (returned!) {
setState(() {
connected = true;
});
}
}
_print() async {
try {
var data = Uint8List.fromList(
utf8.encode(" Hello world Testing ESC POS printer..."));
await flutterUsbPrinter.write(data);
// await FlutterUsbPrinter.printRawData("text");
// await FlutterUsbPrinter.printText("Testing ESC POS printer...");
} on PlatformException {
//response = 'Failed to get platform version.';
}
}
@override
Widget build(BuildContext context) {
return new MaterialApp(
home: new Scaffold(
appBar: new AppBar(
title: new Text('USB PRINTER'),
actions: <Widget>[
new IconButton(
icon: new Icon(Icons.refresh),
onPressed: () => _getDevicelist()),
connected == true
? new IconButton(
icon: new Icon(Icons.print),
onPressed: () {
_print();
})
: new Container(),
],
),
body: devices.length > 0
? new ListView(
scrollDirection: Axis.vertical,
children: _buildList(devices),
)
: null,
),
);
}
List<Widget> _buildList(List<Map<String, dynamic>> devices) {
return devices
.map((device) => new ListTile(
onTap: () {
_connect(int.parse(device['vendorId']),
int.parse(device['productId']));
},
leading: new Icon(Icons.usb),
title: new Text(
device['manufacturer'] + " " + device['productName']),
subtitle:
new Text(device['vendorId'] + " " + device['productId']),
))
.toList();
}
}