Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 680
Andreas Hunter Avatar asked Nov 24 '25 15:11

Andreas Hunter


1 Answers

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.

like image 166
Afridi Kayal Avatar answered Nov 27 '25 04:11

Afridi Kayal



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!