First of all, there is no easy way. You must learn at least some basics of Bluetooth protocol if you want to work with it successfully. Of course, don't waste time trying to implement Bluetooth from scratch. Use packages and you will learn everything while writing code, reading documentation and debugging.
I'm using Flutter Blue package. It works both with other phones and any auxiliary devices. Example in description works perfectly. Everything that goes on top should be custom to your app; therefore there is no need to look for other code snippets.
Working with Bluetooth may be harder because the hardware component is involved. In cases like that debugging complexity grows exponentially. Split the process into smaller parts and you will be okey: scanning, detection, address read, connection, and so on.
This is a general code snippet to scan available devices. If the device is detected- the name is represented.
class BleScan extends StatefulWidget {
@override
_BleScanState createState() => _BleScanState();
}
class _BleScanState extends State<BleScan> {
BluetoothService service;
int scanDuration = 10; // seconds
@override
void initState() {
FlutterBlue.instance.startScan(timeout: Duration(seconds: scanDuration));
super.initState();
}
@override
Widget build(BuildContext context) {
return Column(
children: <Widget>[
Container(
alignment: Alignment.center,
child: Text('Search again if not detected'),
),
StreamBuilder<List<ScanResult>>(
stream: FlutterBlue.instance.scanResults,
initialData: [],
builder: (c, snapshot) => Column(
children: snapshot.data
.where((t) => t.device.name.contains(serialNumberMap[chosenSerial])) //Filter by name
.map(
(r) => Text(r.device.name),
)
.toList(),
),
),
Spacer(),
Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
StreamBuilder<bool>(
stream: FlutterBlue.instance.isScanning,
initialData: false,
builder: (c, snapshot) {
if (snapshot.data) {
return Container();
} else {
return FloatingActionButton.extended(
icon: Icon(Icons.search),
label: Text('Search again'),
onPressed: () {
FlutterBlue.instance.startScan(timeout: Duration(seconds: scanDuration));
},
);
}
},
),
],
),
],
);
}
}
This snippet can be used to connect to the device, read services and characteristics. Take a note that characteristic is a location where data exchange is happening as documented everywhere.
widget.device.connect(timeout: const Duration(seconds: 5), autoConnect: false).then((a) {
widget.device.discoverServices().then((value) {
value.forEach((service) {
//services are here
service.characteristics.forEach((characteristic) {
//characteristics
});
});
});
});