@@ -30,6 +30,7 @@ import 'package:flutter_localizations/flutter_localizations.dart';
30
30
import 'package:flutter_localized_locales/flutter_localized_locales.dart' ;
31
31
import 'package:workmanager/workmanager.dart' ;
32
32
import 'package:yaml/yaml.dart' ;
33
+ import 'package:connectivity_plus/connectivity_plus.dart' ;
33
34
34
35
const String backgroundUploadTask = 'backgroundUploadTask' ;
35
36
const String backgroundBluetoothSubscribeTask = 'backgroundBluetoothSubscribeTask' ;
@@ -141,11 +142,22 @@ class EnsembleAppState extends State<EnsembleApp> with WidgetsBindingObserver {
141
142
// the entire App to reload (e.g. change Locale at runtime)
142
143
Key ? appKey;
143
144
145
+ bool _hasInternet = true ;
146
+ late final StreamSubscription <List <ConnectivityResult >>
147
+ _connectivitySubscription;
148
+
144
149
@override
145
150
void initState () {
146
151
super .initState ();
147
152
WidgetsBinding .instance.addObserver (this );
148
153
config = initApp ();
154
+
155
+ // Initialize connectivity listener.
156
+ _updateConnectivity ();
157
+ _connectivitySubscription = Connectivity ()
158
+ .onConnectivityChanged
159
+ .listen ((_) => _updateConnectivity ());
160
+
149
161
// Initialize native features.
150
162
if (! kIsWeb) {
151
163
Workmanager ().initialize (callbackDispatcher, isInDebugMode: false );
@@ -173,6 +185,23 @@ class EnsembleAppState extends State<EnsembleApp> with WidgetsBindingObserver {
173
185
}
174
186
}
175
187
188
+ /// Check the device’s connectivity and update the state.
189
+ Future <void > _updateConnectivity () async {
190
+ final result = await Connectivity ().checkConnectivity ();
191
+ final hasInternetNow = result.any ((r) => r != ConnectivityResult .none);
192
+
193
+ // If connectivity has been restored, reinitialize the app
194
+ if (! _hasInternet && hasInternetNow) {
195
+ setState (() {
196
+ config = initApp ();
197
+ });
198
+ }
199
+
200
+ setState (() {
201
+ _hasInternet = hasInternetNow;
202
+ });
203
+ }
204
+
176
205
@override
177
206
void didChangeAppLifecycleState (AppLifecycleState state) async {
178
207
super .didChangeAppLifecycleState (state);
@@ -192,6 +221,7 @@ class EnsembleAppState extends State<EnsembleApp> with WidgetsBindingObserver {
192
221
193
222
@override
194
223
void dispose () {
224
+ _connectivitySubscription.cancel ();
195
225
WidgetsBinding .instance.removeObserver (this );
196
226
super .dispose ();
197
227
}
0 commit comments