Check connectivity in flutter and change state according connection status

Viewed 1260

I'm new to Flutter and connectivity. I try connectivity package it works but I want to implement in existing app. If there is connection available then open HomePage() state, otherwise refer to another state. Please help me.

Here's my code https://pastebin.com/3wbDiF8j (main.dart). https://pastebin.com/vPUYUdgc (noInternet.dart)

2 Answers

Use Connectivity Plus package and return MaterialApp using StreamBuilder. In this way, you won't have to check for connection on every single page.

StreamBuilder(
        stream: Connectivity().onConnectivityChanged,
        builder: (context, AsyncSnapshot<ConnectivityResult> snapshot) {
          return snapshot.data == ConnectivityResult.mobile ||
                  snapshot.data == ConnectivityResult.wifi
              ? OnlineMaterialApp()
              : OfflineMaterialApp();
        },
      ),

For a starter, You can listen for changes, for example in your onInit method at the top of your app:

connectivity.onConnectivityChanged
        // .distinct()  (from rxdart package, uncomment if you have this dep)
        // debounce time for epileptic network
        // .debounceTime(_debounceTime)  (from rxjs package)
        .listen((c) => setState(() => connectivity = c));

in your build method you can now use the value.

This has to wrap your applications pages, to do so you can set the above listener in a widget that will display the right child depending on the connectivity state and use that widget in the build method:

MaterialApp(
  // ...
  builder: (ctx, child) => ConnectivityWrapper(child)
)

and in ConnectivityWrapper onInit

connectivity.onConnectivityChanged
        // .distinct()  (from rxjs package, uncomment if you have this dep)
        // .debounceTime(Duration(milliseconds: 400))  (from rxjs package)
        .listen((c) => setState(() => connectivity = c));

In connectivity wrapper build:

if (connectivity == ConnectivityResult.none) 
  return NoInternetPage();
return child;
Related