I am new to Bluetooth and this is the first time I am trying it, so I am trying to develop an application that scans for nearby Bluetooth devices and connects, I am using flutter_blue package and I wrote this simple code to scan for devices, and there are two devices near it but when I run the app (real phone) it does not discover them, I want to know what is wrong with my code, I need help please.
class _MyHomePageState extends State<MyHomePage> {
final FlutterBlue flutterBlue= FlutterBlue.instance;
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: Text("BLE"),),
body: StreamBuilder<BluetoothState>(
stream:flutterBlue.state,
builder: (context, snapshot){
if(snapshot.data == BluetoothState.on)
{
return ScanForDevices(flutterBlue: flutterBlue,);
//return Center(child: Text("${snapshot.data!.toString()}"),);
}
else if(snapshot.hasError ||snapshot.data == BluetoothState.unauthorized)
{
return Center(child: Text("Error"),);
}
else{
return Center(child: CircularProgressIndicator(),);
}
},
),
);
}
}
class _ScanForDevicesState extends State<ScanForDevices> {
late List<ScanResult> result ;
@override
void initState() {
// TODO: implement initState
super.initState();
widget.flutterBlue.startScan();
// scanning();
}
scanning() {
widget.flutterBlue.scanResults.listen((event) {
for(ScanResult r in event)
{
result.add(r);
print(r.device.id.toString() + "\n");
}
});
}
@override
Widget build(BuildContext context) {
return Scaffold(
body: StreamBuilder<List<ScanResult>>(
stream:FlutterBlue.instance.scanResults,
builder: (context, snapshot){
if(snapshot.hasData)
{
return ListView(
// children: snapshot.data!.map((e) {
// return Text("${e.device.id.toString()}");
// }).toList(),
children: snapshot.data!.map((e) => ListTile(
leading: IconButton(
icon: Icon(Icons.present_to_all_sharp),
onPressed: (){e.device.connect(timeout: Duration(seconds: 4),);},),
subtitle: Text("${e.device.name }\n ${e.device.id.id}"),
title: Text(e.device.id.toString()))).toList()
// result.map((e) {
// return Text(e.device.id.toString());
// }).toList(),
);
}
if(snapshot.hasError)
{
return Text("Error");
}
else {
return CircularProgressIndicator();
}
},
),
);
}
}