flutterbluetoothlistenerstate-management

Flutter blue plus connection state listener


I have an app that uses flutter_blue_plus and I want to add a listener to the connection state of the device. As soon as the device loose connection I want to show a popup anywhere inside my app to inform the user that they lost connection. I have multiple screens so where should I setup the listener so it can popup anywhere in my app? If I set up my listener in 'main.screen' will it be able to show popup all around the app?

I connect to my device on my 'main.screen'

This is the documentation from flutter_blue_plus:

    // tip: using ??= makes it easy to only make new listener when currently null
final subscription ??= FlutterBluePlus.device.connectionState.listen((value) {
    // ...
});

// also, make sure you cancel the subscription when done!
subscription.cancel()

How can I use this globally in my app?


Solution

  • Call your code after connecting to the device and it should work within the app until you call the .cancel() function

    Connect to your device and then call:

    final subscription ??= FlutterBluePlus.device.connectionState.listen((value) {
        // ...
    });
    

    Disconnect or when you don't want to listen anymore:

    subscription.cancel()