I want to check for internet connection at every screen on my app just like Telegram does and whenever user goes offline, show an Offline banner on the top of the screen.
I have tried using connectivity_plus and internet_connection_checker plugins to check for this but the problem is I have to subscribe to a stream for this and if the device goes offline once then there is no way to subscribe to it again without clicking a button.
getConnectivity() =>
subscription = Connectivity().onConnectivityChanged.listen(
(ConnectivityResult result) async {
isDeviceConnected = await InternetConnectionChecker().hasConnection;
if (!isDeviceConnected && isAlertSet == false) {
setState(() {
constants.offline = true;
print('Constants().offline ${constants.offline}');
isAlertSet = true;
});
}
print('off');
},
);
I’m using this code right now to check this issue but I don’t want to replicate this code on each and every screen and even if I do replicate it then there will be a lot of subscriptions that I’ll be subscribing to, which will mean that all the subscriptions will be disposed at the same time causing all sorts of issues.
4
Answers
I myself use connectivity_plus and I have never found the problem you mentioned (if the device goes offline once then there is no way to subscribe to it again without clicking a button), you can use my example.
If the user’s internet is disconnected, a modal will appear. If the user is connected again, the modal will be deleted automatically.
Anyway, I put the option to check the internet again in the modal
If you have custom
Scaffold
, then you have to edit it. Otherwise, create a new one and change allScaffold
s to your custom one. This allows you to easily apply changes that should be on all pages.Then, in the
CustomScaffold
create aStack
that contains page content andValueListenableBuilder
that listens to connection changes and if there is no internet displays error banner.only screen widgets contains Scaffold
to extends BaseScreenWidgetUSE THIS SIMPLE TECHNIQUE only need this package: Internet Connection Checker. If you turn off your network it will tell you
connection_checker.dart
base.dart