flutter_reactive_ble如何停止扫描

huangapple go评论74阅读模式
英文:

flutter_reactive_ble how to stop scan

问题

I understand that you want a translation of your provided code. Here is the translated code:

我正在使用flutter_reactive_ble库与我的打印机进行通信。它正常工作,但如果我点击开始扫描设备,它就无法停止了。

我在这里发布我的代码:

void searchingDevice() {
  print('搜索设备');
  try {
    scanStream = flutterReactiveBle.scanForDevices(withServices: [], scanMode: ScanMode.lowLatency).listen((device) {
      if (device.name != "") {
        _addDeviceTolist(device.id, device.name);
      }
    }, onError: (e) {
      print(e.name);
      //处理错误的代码
    });
  } catch (e) {
    showDialog(
      context: context,
      builder: (_) {
        return AlertDialog(
          title: Text('ALARM'),
          content: Text(e.toString()),
        );
      });
  }
}

Future<void> refresh() async {
  searchingDevice();
}

@override
Widget build(BuildContext context) {
  return MaterialApp(
    debugShowCheckedModeBanner: false,
    home: Scaffold(
      appBar: AppBar(
        title: Text('蓝牙设备'),
        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: '蓝牙设备', value: connectDeviceId);
                            await Future.delayed(const Duration(seconds: 1));
                            // Navigator.pop(context);
                            //Navigator.of(context).pop();
                            //Navigator.pushNamed(context, bluetoothState.routeName);
                          }, child: Text('连接'))]
                    ),
                  ],
                ),
              );
            }),
      ),
    ),
  );
}

Please note that I've translated your code, but I haven't made any changes to the functionality. If you have specific questions or need further assistance, please let me know.

英文:

im using flutter_reactive_ble library to communicate with my print.It works normally,but if i click to start scan devices,it can't stop anymore.

I post here my codes:


void searchingDevice() {
print(&#39;searching device&#39;);
try {
scanStream= flutterReactiveBle.scanForDevices(withServices: [], scanMode: ScanMode.lowLatency).listen((device) {
if (device.name != &quot;&quot;) {
_addDeviceTolist(device.id, device.name);
}
}, onError: (e) {
print(e.name);
//code for handling error
});
} catch (e) {
showDialog(
context: context,
builder: (_) {
return AlertDialog(
title: Text(&#39;ALARME&#39;),
content: Text(e.toString()),
);
});
}
}
Future&lt;void&gt; refresh() async {
searchingDevice();
}
@override
Widget build(BuildContext context) {
return MaterialApp(
debugShowCheckedModeBanner: false,
home: Scaffold(
appBar: AppBar(
title: Text(&#39;BLUETOOTH DEVICE&#39;),
leading: IconButton(
icon: const Icon(Icons.arrow_back),
onPressed: () =&gt;
Navigator.pushNamed(context, bluetoothState.routeName),
// connectBlue(&quot;04F9F6C0-04F3-FB6A-9DA7-48AC0BD087C6&quot;),
),
),
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: &lt;Widget&gt;[
Column(
mainAxisAlignment: MainAxisAlignment.start,
crossAxisAlignment: CrossAxisAlignment.start,
children: &lt;Widget&gt;[
Text(devices[index].deviceName!),
Text(devices[index].id!),
],
),
Column(
mainAxisAlignment: MainAxisAlignment.end,
crossAxisAlignment: CrossAxisAlignment.start,
mainAxisSize: MainAxisSize.max,
children:&lt;Widget&gt;[ElevatedButton(onPressed: () async{
connectDeviceId=devices[index].id.toString();
connectBlue(connectDeviceId);
await storage.write(key: &#39;bluetoothDevice&#39;, value: connectDeviceId);
await Future.delayed(const Duration(seconds: 1));
// Navigator.pop(context);
//Navigator.of(context).pop();
//Navigator.pushNamed(context, bluetoothState.routeName);
}, child: Text(&#39;CONNECT&#39;))] )
],
),
);
}),
),
),
);

So if i click on the button to refresh ,it gives me error because i think maybe in the background the device is still scanning.

Thanks in advance and best regards

答案1

得分: 1

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

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

英文:

According to this question on the flutter_reactive_ble repository you need to cancel the subscription to scanStream you opened using the listen() method. This can be done by calling cancel() on the stream:

> After this call, the subscription no longer receives events.
> The stream may need to shut down the source of events and clean up after the subscription is canceled.
> Returns a future that is completed once the stream has finished its cleanup.

huangapple
  • 本文由 发表于 2023年4月11日 01:28:12
  • 转载请务必保留本文链接:https://go.coder-hub.com/75979261.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定