Flutter_blue: How to scan for ever

Created on 17 Nov 2020  路  4Comments  路  Source: pauldemarco/flutter_blue

Hello
How can I use flutter blue to detect when I enter my car and my phone connects to my car (they have paired already).
I want to use it to automatically start music playback in my app.
Is it logical to scan for ever:
flutterBlue.startScan(timeout: Duration(seconds: 9999999999));
Thanks

Most helpful comment

Hi, if you want to scan repeatedly. u must not use duration, just use flutterBlue.startScan();

All 4 comments

Hi , did you have any solution ?
they should add a function like onScanFinished() to restart a new Scan

after some search, Here is my solution
in Dart Language , we can use a Stream object

      @override
       void initState() {
               setStream(getScanStream());
      }

      Stream<ScanResult> getScanStream() {
          return FlutterBlue.instance.scan(timeout: Duration(seconds: 10));
      }

      void setStream(Stream<ScanResult> stream) async {
        stream.listen((event) {
            print("data received $event");
        }, onDone: () async{

            // Scan is finished ****************
            await FlutterBlue.instance.stopScan();
            print("Task Done");
            print("second scan");
            setStream(getScanStream()); // New scan

        }, onError: (Object e) {
            print("Some Error "  + e.toString());
        });
  }

Hi, if you want to scan repeatedly. u must not use duration, just use flutterBlue.startScan();

@Chakib-Temal Thank you for this solution. This is really good, you have a lot more control. Also flutterBlue.startScan(); will stop working when you manually turn bluetooth on and off.

Was this page helpful?
0 / 5 - 0 ratings