I've been struggling lately with flutter and its flutterblue module to accomplish reading and writing data to a bluetooth device, but I happens no chance to achieve what I need.
Below is my code to scan for devices and their data:
@override
Widget build(BuildContext context) {
FlutterBlue.instance.startScan(timeout: Duration(seconds: 4), scanMode: ScanMode.lowPower);
return Scaffold(
body:StreamBuilder<List<ScanResult>>(
stream: FlutterBlue.instance.scanResults.asBroadcastStream(),
initialData: [],
builder: (c, snapshot) {
List <ScanResult> results = snapshot.data;
return ListView.separated(
itemBuilder: (context, index){
var device = results[index].device;
var name = device.name.length > 0? device.name:"Unknown";
return ListTile(
title: Text(name),
subtitle: Text(device.id.toString()),
trailing: RaisedButton(
child: Text("connect"),
onPressed: () {
if( results[index].advertisementData.connectable == true) {
device.connect();
device.state.listen((event) async {
print("The device state is now ${event}");
});
}
else{
showDialog(context: context, builder: (d){
return AlertDialog(content: Text("The device is not connectable"));
});
}
},
),
);
},
separatorBuilder: (context, index){
return Divider();
},
itemCount: results.length
);
},
),
);
}
Unfortunately, however much I tried, the scan results' devices show no any useful data than empty values, device id and manufacturer data, what I want is to grab the device data, including name and from the grabbed data, calculate the distance to the scanned device. I wonder if this can be achieved in Flutter anyway.
Your help will be much much much appreciated! Thanks.