'Flutter -Plateform Exception For Bluetooth Connnection
I am trying to Connect to a device using Bluetooth on Android platform. Here I am using a plugin called flutter Bluetooth serial for Bluetooth connection. With this plugin I am able to connect to Bluetooth devices like Speakers, Earphones. But, when I am trying to connect to a Mobile Phone/Laptop it gives me error Platform Exception. How do I resolve this issue, can you please help me out. Below is a sample code for Bluetooth connection in flutter that which I am using..
```class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: BluetoothApp(),
);
}
}
class BluetoothApp extends StatefulWidget {
@override
_BluetoothAppState createState() => _BluetoothAppState();
}
class _BluetoothAppState extends State<BluetoothApp> {
var sender;
var dataLength;
**Initializing the Bluetooth connection state to be unknown**
BluetoothState _bluetoothState = BluetoothState.UNKNOWN;
**Get the instance of the Bluetooth**
FlutterBluetoothSerial bluetoothSerial = FlutterBluetoothSerial.instance;
**Track the Bluetooth connection with the remote device**
BluetoothConnection? connection;
int deviceState = 0;
bool isDisconnecting = false;
**To track whether the device is still connected to Bluetooth**
bool get isConnected => connection != null && connection!.isConnected;
List<BluetoothDevice> devices = List.empty(growable: true); **For getting list of Bluetooth device which are enabled **
BluetoothDevice? device;
bool connected = false;
bool _isButtonUnavailable = false;
bool enabled = false;
@override
void initState() {
super.initState();
deviceState = 0;
// Listen for further state changes
FlutterBluetoothSerial.instance
.onStateChanged()
.listen((BluetoothState state) {
setState(() {
_bluetoothState = state;
if (_bluetoothState == BluetoothState.STATE_OFF) {
_isButtonUnavailable = true;
}
searchForBluetoothDevices(); **This Method is used to Discover the Bluetooth devices**
});
});
enableBluetooth(); **This Method is used for asking Bluetooth permission**
}
@override
void dispose() {
// Avoid memory leak and disconnect
if (isConnected) {
isDisconnecting = true;
connection!.dispose();
connection = null;
}
super.dispose();
}
** Request Bluetooth permission from the user**
Future<bool> enableBluetooth() async {
** Retrieving the current Bluetooth state**
_bluetoothState = await FlutterBluetoothSerial.instance.state;
** If the bluetooth is off, then turn it on first**
** and then retrieve the devices that are Discovered.**
if (_bluetoothState == BluetoothState.STATE_OFF) {
enabled = (await FlutterBluetoothSerial.instance.requestEnable())!;
if (enabled == true) {
searchForBluetoothDevices();
} else {}
return true;
} else {
searchForBluetoothDevices();
}
return false;
}
void searchForBluetoothDevices() {
try {
bluetoothSerial.startDiscovery().listen((result) {
setState(() {
devices.add(result.device); **Used to add devices to List after Discovered**
});
}).onDone(() {
print("Discovery Stopped");
connected = false;
});
} on PlatformException {
print("Error");
}
** It is an error to call [setState] unless [mounted] is true.**
if (!mounted) {
return;
}
}
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
key: _scaffoldKey,
appBar: AppBar(
title: Text("Flutter Bluetooth"),
),
body: Container(
child: Column(
mainAxisSize: MainAxisSize.max,
children: <Widget>[
ListView(
shrinkWrap: true,
children: devices
.map((e) => ListTile(
title: Text(e.name ?? ''),
trailing: ElevatedButton(
onPressed: () => _isButtonUnavailable
? null
: connected
? disconnect()**Used to Disconnect the device**
: connect(e.address), **Used to connect the Device by sending the Bluetooth address to this method**
child: Text(connected ? 'Disconnect' : 'Connect'),
),
))
.toList(),
),
],
),
),
/* floatingActionButton: FloatingActionButton(
onPressed: () => enableBluetooth(),
child: Icon(Icons.find_replace),
), */
),
);
}
** Method to connect to bluetooth**
void connect(String deviceAddress) async {
setState(() {
_isButtonUnavailable = true;
});
if (deviceAddress == null) {
show('No device selected');
} else {
if (!isConnected) {
await BluetoothConnection.toAddress(deviceAddress).then((_connection)***Plateform Exception*** {
print('Connected to the device');
connection = _connection;
setState(() {
connected = true;
});
connection!.input!.listen(null).onDone(() {
if (isDisconnecting) {
print('Disconnecting locally!');
} else {
print('Disconnected remotely!');
}
if (this.mounted) {
setState(() {});
}
});
}).catchError((error) {
print('Cannot connect, exception occurred');
print(error);
});
setState(() => _isButtonUnavailable = false);
}
}
}
** Method to disconnect bluetooth**
void disconnect() async {
setState(() {
_isButtonUnavailable = true;
deviceState = 0;
});
await connection!.close();
show('Device disconnected');
if (connection!.isConnected) {
setState(() {
connected = false;
_isButtonUnavailable = false;
});
}
}```
<PlatformException (PlatformException(connect_error, read failed, socket might closed or timeout, read ret: -1, java.io.IOException: read failed, socket might closed or timeout, read ret: -1
at android.bluetooth.BluetoothSocket.readAll(BluetoothSocket.java:940)
at android.bluetooth.BluetoothSocket.readInt(BluetoothSocket.java:954)
at android.bluetooth.BluetoothSocket.connect(BluetoothSocket.java:502)
at io.github.edufolly.flutterbluetoothserial.BluetoothConnection.connect(BluetoothConnection.java:57)
at io.github.edufolly.flutterbluetoothserial.BluetoothConnection.connect(BluetoothConnection.java:64)
at io.github.edufolly.flutterbluetoothserial.FlutterBluetoothSerialPlugin.lambda$onMethodCall$0$FlutterBluetoothSerialPlugin(FlutterBluetoothSerialPlugin.java:880)
at io.github.edufolly.flutterbluetoothserial.-$$Lambda$FlutterBluetoothSerialPlugin$IghJwXXwUz_TFyaj49DgLpHhUY4.run(Unknown Source:10)
at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:289)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1167)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:641)
at java.lang.Thread.run(Thread.java:919)
, null))
<Is their any other Plugin to use for bluetooth connection except flutter_bluetooth_serial.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
