flutter_reactive_ble如何停止扫描



我使用flutter_reactive_ble库与我的打印进行通信。它工作正常,但如果我点击启动扫描设备,它不能停止了。

我把我的代码贴在这里:


void searchingDevice() {
print('searching device');
try {
scanStream= flutterReactiveBle.scanForDevices(withServices: [], scanMode: ScanMode.lowLatency).listen((device) {
if (device.name != "") {
_addDeviceTolist(device.id, device.name);
}
}, onError: (e) {
print(e.name);
//code for handling error
});
} catch (e) {
showDialog(
context: context,
builder: (_) {
return AlertDialog(
title: Text('ALARME'),
content: Text(e.toString()),
);
});
}
}

Future<void> refresh() async {
searchingDevice();
}
@override
Widget build(BuildContext context) {
return MaterialApp(
debugShowCheckedModeBanner: false,
home: Scaffold(
appBar: AppBar(
title: Text('BLUETOOTH DEVICE'),
leading: IconButton(
icon: const Icon(Icons.arrow_back),
onPressed: () =>
Navigator.pushNamed(context, bluetoothState.routeName),
// connectBlue("04F9F6C0-04F3-FB6A-9DA7-48AC0BD087C6"),
),
),

body: RefreshIndicator(
onRefresh: () async {
refresh();
},
child: ListView.builder(
itemCount: devices.length,
itemBuilder: (context, index) {
return Container(
decoration: BoxDecoration(
border: Border.all(),
),
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: <Widget>[
Column(
mainAxisAlignment: MainAxisAlignment.start,
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
Text(devices[index].deviceName!),
Text(devices[index].id!),
],
),
Column(
mainAxisAlignment: MainAxisAlignment.end,
crossAxisAlignment: CrossAxisAlignment.start,
mainAxisSize: MainAxisSize.max,
children:<Widget>[ElevatedButton(onPressed: () async{
connectDeviceId=devices[index].id.toString();
connectBlue(connectDeviceId);
await storage.write(key: 'bluetoothDevice', value: connectDeviceId);
await Future.delayed(const Duration(seconds: 1));
// Navigator.pop(context);
//Navigator.of(context).pop();
//Navigator.pushNamed(context, bluetoothState.routeName);
}, child: Text('CONNECT'))] )
],
),
);
}),
),

),
);

所以如果我点击按钮刷新,它会给我错误,因为我认为可能在后台设备仍在扫描。

提前感谢并致以最良好的问候

根据flutter_reactive_ble存储库上的这个问题,您需要取消使用listen()方法打开的scanStream订阅。这可以通过在流上调用cancel()来完成:

调用后,订阅不再接收事件。
订阅取消后,流可能需要关闭事件源并进行清理。
返回一个在流完成清理后完成的future。

相关内容

  • 没有找到相关文章

最新更新