connect method
connect let you connect to a bluetooth printer
Implementation
Future connect({Duration? timeout = const Duration(seconds: 5)}) async {
try {
if (Platform.isAndroid) {
final bluetooth = DragoBluePrinter.instance;
List<BluetoothDevice> devices = [];
try {
devices = await bluetooth.getBondedDevices();
} catch (e) {
return Future.error("Failed to get bonded devices: $e");
}
BluetoothDevice? device;
try {
device = devices.firstWhere((d) => d.address == printer.address);
} catch (e) {
// If not in bonded, try to create from address if possible or error
// Assuming user might want to connect to non-bonded if scan found it?
// DragoBluePrinter.connect takes BluetoothDevice.
// We can construct one if we have name and address, or strict bonded check.
// sticking to bonded check for now as per previous logic structure,
// but if scan() works, we might want to allow connecting to scanned devices.
// Let's create a temporary device object if not found in bonded,
// assuming the underlying plugin can handle it.
device = BluetoothDevice(printer.name ?? "Unknown", printer.address!);
}
// Check if already connected
bool? isConnected = await bluetooth.isConnected;
if (isConnected == true) {
// Determine if connected to the *correct* device might be hard without `connectedDevice` info
// but usually we can disconnect and reconnect or just assume success if we want to be safe.
// However, safe practice:
await bluetooth.disconnect();
}
await bluetooth.connect(device);
} else if (Platform.isIOS) {
Map<String, dynamic> params = {
"name": printer.name,
"address": printer.address,
};
await iosChannel.invokeMethod('connect', params);
}
} catch (e) {
if ((e as dynamic).message == "already connected") {
await disconnect();
await connect();
} else
return Future.error(e.toString());
}
}