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?
2
Answers
The solution depends on the target operating system. For Android it sounds like you want to use a
notification
orsnackbar
Notifications are messages that Android displays outside your app’s UI to alert users to reminders, communications from other people, or other timely information from your app. Users can tap the notification to open your app or take an action directly from the notification.
Snackbars are a quick message to the user without necessarily waiting for the user to respond.
The solution you are looking for can be done in Flutter and does not require any interaction with the native OS platforms.
You can setup a listener widget that wraps your app and then allows you to display a popup anywhere in your app. Here is an example.
Let’s assume this is how your app is structured using MaterialApp.router. The key here is to use the
builder
method that allows you to put a "wrapper" widget on top of all your app’s screens. See the Flutter Docs for additional information about the builder method. I have named this wrapperAppWrapperListener
.The
AppWrapperListener
can be a stateful or stateless widget based on your needs. Then you can utilize theshowDialog
orshowBanner
to show your popup as needed.