Search code examples
flutterdartconnectivity

Check connectivity in flutter and change state according connection status


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)


Solution

  • 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();
            },
          ),