Detect Internet Connection in Flutter

We will see how we can detect Internet connection in a Flutter application using a package.

I'm going to show you how you can check the internet connection in a Flutter application, for that I'm using the following package:

import 'package:connectivity_plus/connectivity_plus.dart';
$ flutter pub add connectivity_plus

Here you can see the compatibility it has So it's a bit the same you open the you come here installation better said copy the name you put the version if you want if not don't put it etcetera once installed you import it where you want to do the verification in this case I am using the custom scaffold that remember that it is a special widget that I created before I already showed you this there I leave it attached in case you want to see it but it is a widget that I use to place it on all my pages on all the pages that I have for my application which are all the ones you can see here that is to say all the ones I have here rotated at the application level use this custom scaffold since apart from being able for example to customize where I want to place the dware and others it is also useful for this type of situations in which we want to do some prior check before each page before the user can enter each page as in this case it would be for example the internet connection although that implementation a bit where you want to place it depends on you anyway in the end it is a widget like any other a stateful widget and what matters is how you use it We use it here in the inck State which Remember that it is the one that is executed according to the life cycle of an application in Flutter or one of the first or at least before the build one which is used to build our widget:

  @override
 void initState() {
   init();
   super.initState();
 }
 Future<bool> checkIsInternetConnection() async {
   var connectivityResult = await (Connectivity().checkConnectivity());
   return ConnectivityResult.none != connectivityResult;
 }
 init() async {
   _thereIsInternet = await checkIsInternetConnection();
   if (!_thereIsInternet) {
     // no hay internet
     setState(() {});
   }
 }

Explaining the above code

So I don't check this here directly because right now I'm going to tell you why but remember that here the problem that we have is that it is complicated to put it as asynchronous type because even if it accepts it Here there are several problems that can happen So what I did was Simply put that part of asynchronous type in another method So here I simply invoke it notice that I'm not doing any blocking right now we see how we do this here we have the method and here we have the method that we are invoking here that I would use to do any initialization that in this case I only need to verify the internet connection so how it works here I have a noise that is this this is by default true that is to say by default I am indicating that it has internet which I think would be the healthiest and I check it through this function this method that as you can see is of type weight That is to say of type asynchronous here we have all this is of type asynchronous.

Here I expect the result, the good result can return several things but for practical purposes we are interested in whether there is no connection, therefore if there is no connection here it returns the following object which would be the connection resve null point here you can see the rest in case you are interested if it is by ethernet if it is mobile if it is WiFi here you can see all that but again we are interested in when we do not have a connection not the type of connection and we verify it here the answer:

ConnectivityResult

For some reason I did this the other way around or as one is used to it, it could perfectly be like this but well I did it the other way around for some reason, I'm going to leave it like this here we check if it is equal if it is equal to this it means that we do not have internet therefore it would return a false and therefore we do not have internet and in that case you do something:

return  connectivityResult != ConnectivityResult.none

So here as you can guess and just as you are seeing in the code this is an asynchronous request all connections that are to disk or to the internet are asynchronous for obvious reasons and that is where we do the blocking, notice that I put the blocking in quotes since other times it is a little difficult to place in certain important methods for us in the without and the wit when we are working with this full widget blocking methods here such as in setState and the build one, then I put the blocking in quotes what I do is to not use a Future simply when there is no internet is that I reload the entire page and it is reloaded using setState and that is what I am doing, so what we do is run the build again and in the build what I do is check the internet connection if there is no connection then I paint any other type of widget:

@override
 Widget build(BuildContext context) {
   if (!_thereIsInternet) {
     // no hay conexion
     return Scaffold(
       appBar: AppBar(
         title: Text(widget.title),
       ),
       body: SizedBox(
         width: double.infinity,
         child: Column(
           mainAxisAlignment: MainAxisAlignment.center,
           crossAxisAlignment: CrossAxisAlignment.center,
           children: [
             Text(LocaleKeys.thereIsNoInternet.tr()),
             const SizedBox(height: 15),
             MaterialButton(
               color: Theme.of(context).primaryColor,
               textTheme: Theme.of(context).buttonTheme.textTheme,
               // textTheme: Theme.of(context).buttonTheme,
               onPressed: () async {
                 await init();
                 if (_thereIsInternet) {
                   // navega a alguna pagina para regargar
                   Navigator.pushReplacement(
                       context,
                       MaterialPageRoute(
                           builder: (context) => ListPage(
                               false, 0, 0, '', LocaleKeys.lastsPosts.tr())));
                   // setState(() {});
                   // no llama al metodo de build
                   // Navigator.pushReplacement(
                   //     context,
                   //     MaterialPageRoute(
                   //         builder: (BuildContext context) => super.widget));
                 }
               },
               child: Text(LocaleKeys.reload.tr(),
                   style: Theme.of(context)
                       .textTheme
                       .bodyLarge!
                       .copyWith(color: Colors.white)),
             ),
           ],
         ),
       ),
     );
   }

In this case with a button in the middle that navigates well with a button in the middle that says there is no internet which is the message that I am placing here but when there is already a connection or when I want better said when the user wants to verify the connection what I do is place a button here then we call the method that I showed you before and And if this finally makes There is internet true that is to say that there is internet I show or navigate to a specific page in this case the list of publications again this is a button that will always be present and what it does is every time the user presses it verify if there is an internet connection what this verification does in the end is set this to true And if this is true then I can perfectly navigate to another page and for the purposes of the user You are seeing that it will be loading the application in this case the best thing was to load the current page but that is a bit complicated or I have not seen the way to do it I do not know well there is no way as who says or as far as I have investigated official to reload a page then to avoid that annoyance since I cannot do as who says from the application cannot do a hor reload or something like that what I do is a navigation to another page doing a push replacement:

Navigator.pushReplacement(
                       context,
                       MaterialPageRoute(
                           builder: (context) => ListPage(
                               false, 0, 0, '', LocaleKeys.lastsPosts.tr())));

So replace this page and we've already gotten rid of all the craziness with the navigation part, the internet verification and little else to say, it's that simple. So with these lines of code you can easily check when there is a connection or not and from there act accordingly, that is, if there is no connection, you paint a different interface. Since in this case, suppose it is the publication listing page, it will not build anything because there is no connection and once we have a connection we simply go to a specific page.

- Andrés Cruz

En español

Andrés Cruz

Develop with Laravel, Django, Flask, CodeIgniter, HTML5, CSS3, MySQL, JavaScript, Vue, Android, iOS, Flutter

Andrés Cruz In Udemy

I agree to receive announcements of interest about this Blog.