Search code examples
flutterbluetooth-lowenergyreactive

flutter_reactive_ble how to stop scan


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('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'))] )
                    ],
                  ),
                );
              }),
        ),
       
      ),
    );


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


Solution

  • 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.