Andreas Hunter
Andreas Hunter

Reputation: 5024

How to check internet connection globally and show no connection screen

I use connectivity package in my project to check internet connection.

File main.dart code:

StreamProvider<ConnectivityResult>(
    create: (context) =>
        InternetConnectionService().connectionStatusController.stream,
    child: MaterialApp(
.....

And on each screen I check internet connection like this:

bool hasConnection;

void checkConnectivity(context) async {
  var connectivityResult = Provider.of<ConnectivityResult>(context);
  if (connectivityResult == ConnectivityResult.none ||
      connectivityResult == null) {
    setState(() {
      hasConnection = false;
    });
  } else {
    setState(() {
      hasConnection = true;
    });
  }
}

Widget build(BuildContext context) {
  checkConnectivity(context);
  return hasConnection == true 
    ? Scaffold() 
    : NoInternetScreen();
}

How I check connection globally instead on each screen from root or one widget and show no connection screen?

Upvotes: 2

Views: 8566

Answers (3)

Peacemaker Otoo
Peacemaker Otoo

Reputation: 129

this is what worked for, I displayed the network connectivity inside the global appbar of the MaterialApp, call the builder from the materiaApp:

  builder: (context, child) {
          return StreamBuilder<ConnectivityResult>(
            stream: Connectivity().onConnectivityChanged.expand((event) =>
                event), // Flatten the list to individual ConnectivityResult
            builder: (context, snapshot) {
              final connectivityResult = snapshot.data;
              if (connectivityResult == ConnectivityResult.none ||
                  connectivityResult == null) {
                return Scaffold(
                  appBar: PreferredSize(
                    preferredSize: const Size.fromHeight(50.0),
                    child: AppBar(
                      backgroundColor:
                          connectivityResult == ConnectivityResult.none
                              ? Colors.red.shade800
                              : Colors.green,
                      title: connectivityResult == ConnectivityResult.none
                          ? const Text(
                              'No Internet Connection',
                              style: TextStyle(
                                  color: Colors.white,
                                  fontWeight: FontWeight.w300,
                                  fontSize: 15),
                            )
                          : const Text(
                              'Apptitle',
                              style: TextStyle(color: Colors.white),
                            ),
                      centerTitle: true,
                    ),
                  ),
                  body: child, // Your app's body content
                ); // Display a placeholder or appropriate widget for no connectivity
              }
              return child!; // Return the child widget when connected
            },
          );
        },

Upvotes: 0

Balaji
Balaji

Reputation: 2087

       class ConnectivityUtils {
          static Future<bool> hasConnection() async {
            var connectivityResult = await (Connectivity().checkConnectivity());
            return connectivityResult == ConnectivityResult.mobile || connectivityResult == ConnectivityResult.wifi;
         } 
       }

You can use this class, and you can call hasConnection() before calling API If it is false, you can show the No Connection Screen

Upvotes: 2

Afridi Kayal
Afridi Kayal

Reputation: 2295

In your MaterialApp widget, there is a builder. You can wrap your paths in any widget using the builder. Try doing this:

MaterialApp(
    ...
    builder: (context, child) {
        return StreamBuilder<ConnectivityResult>(
            stream: InternetConnectionService().connectionStatusController.stream,
            builder: (context, snapshot) {
                final conenctivityResult = snapshot.data;
                if (connectivityResult == ConnectivityResult.none || connectivityResult == null) return NoInternetScreen();

                return child;
            }
        );
    }
);

Now you don't have to add any internet logic in other files. You can simply write your build methods excluding them.

Upvotes: 7

Related Questions