scanBluetoothDevices static method
- {Duration? timeout}
Starts a scan for Bluetooth devices and returns a stream of the results.
timeout
: Optionally specifies a duration after which the scan will be stopped.
Example of how to use the scanBluetoothDevices()
function.
This example starts a scan for Bluetooth devices and prints the results to the console.
To use the scanBluetoothDevices()
function, you can do the following:
- Call the
scanBluetoothDevices()
function with the desired timeout. - Listen to the
scanResults
stream to receive the results of the scan. - Print the results of the scan to the console.
The following example shows how to use the
scanBluetoothDevices()
function:
Implementation
static Future<void> scanBluetoothDevices({
Duration? timeout,
}) async {
// Stops any existing scan
final isScanning = _isScanning.latestValue;
if (isScanning == true) {
await stopScan();
}
// Sets the scanning flag to true
_isScanning.add(true);
final responseStream = FlutterNewposSdk._methodStream.stream
.where((m) => m.method == 'OnScanResponse')
.map((m) {
final arguments = m.arguments as Map<Object?, Object?>;
final convertedMap = <dynamic, dynamic>{};
arguments.forEach((key, value) {
if (key is String) {
convertedMap[key] = value;
}
});
return convertedMap;
}).map(
BluetoothDevice.fromMap,
);
// Starts buffering the scan results
final scanBuffer = _BufferStream.listen(responseStream);
// Invokes the platform method to start the scan
await _invokeMethod('scanBlueDevice') as bool;
// Creates a stream of the scan results, filtered for devices that are still present
final outputStream = scanBuffer.stream;
// Creates a list to store the scan results
final output = <DeviceScanned>[];
// Listens to the stream of scan results and pushes them to the `scanResults` stream
_scanSubscription = outputStream.listen((BluetoothDevice? response) {
if (response != null) {
// Converts the BluetoothDevice object to a DeviceScanned object
final sr = DeviceScanned.fromDevice(response);
// Adds or updates the DeviceScanned object in the output list
output.addOrUpdate(sr);
// Pushes the output list to the `scanResults` stream
_scanResultsList.add(List.from(output));
}
});
// Starts a timer to stop the scan after the specified timeout
if (timeout != null) {
_scanTimeout = Timer(_defaultTimeOut, stopScan);
}
}