I am developing a flutter application to list and connect my phone to other devices within the app. So I am using a flutter_bluetooth_serial package. I implemented almost the same the code from the documentation but after calling startDiscovery() function in the app's init state cancelDiscovery is instantly called by the app for no reason. The code successfully ran for first two or three times but starts producing the following error afterwards
D/BluetoothAdapter(15019): startDiscovery(): called by: com.example.bluetooth_app
D/FlutterBluePlugin(15019): Canceling discovery (stream closed)
D/BluetoothAdapter(15019): cancelDiscovery(): called by: com.example.bluetooth_app
Not sure what is going on. I am using flutter 3.7 and package version 0.4.0[latest]
Here's the code for the complete app -
import 'dart:async';
import 'package:flutter/material.dart';
import 'package:flutter_bluetooth_serial/flutter_bluetooth_serial.dart';
class FooPage extends StatefulWidget {
const FooPage({super.key});
@override
State<FooPage> createState() => _FooPageState();
}
class _FooPageState extends State<FooPage> {
List<BluetoothDiscoveryResult> devices = [];
late StreamSubscription<BluetoothDiscoveryResult>
_discoveryStreamSubscription;
@override
void initState() {
super.initState();
_startDiscovery();
}
void _startDiscovery() {
_discoveryStreamSubscription =
FlutterBluetoothSerial.instance.startDiscovery().listen(
(r) {
print('device found');
bool deviceFound = false;
devices.forEach((element) {
if (element.device.address == r.device.address) {
deviceFound = true;
}
});
if (!deviceFound) {
setState(() {
devices.add(r);
});
}
},
);
_discoveryStreamSubscription.onDone(() {
setState(() {
print('stream closed');
// _isDiscovering = false;
});
});
}
@override
Widget build(BuildContext context) {
print(devices);
return Scaffold(
appBar: AppBar(
title: Text("Bluetooth Devices"),
),
body: devices.length == 0
? Center(
child: Text('No Nearby devices can be found currently...'),
)
: ListView(
children: devices
.map(
(e) => ListTile(
title: Text(e.device.name!),
subtitle: Text(e.device.type.stringValue),
),
)
.toList(),
),
);
}
}