简体   繁体   中英

Internet connectivity in flutter

How to implement continuous Internet connectivity check in flutter only once for whole app, I have almost complete app, now I need to add Internet connectivity check, Please help, thanks in advance

  @override
  Widget build(BuildContext context) {
      return StreamBuilder<ConnectivityResult>(
          stream: connectivityStream,
          builder: (context, snapshot) {
            if (snapshot.hasData) {
              final connectivityResult = snapshot.data;
              if (connectivityResult == ConnectivityResult.none) {
                return MaterialApp(
                  debugShowCheckedModeBanner: false,
                  home: NoInternetConnectionScreen(),
                );
              }
              return MaterialApp(
                debugShowCheckedModeBanner: false,
                home: SplashScreen(),
                routes: routes,
              );

            } else if (snapshot.hasError) {

              return MaterialApp(
                debugShowCheckedModeBanner: false,
                home: NoInternetConnectionScreen(),
              );
            }

            return Center(child: CircularProgressIndicator());
          }
      );
  }

The connectivity plugin states in its docs that it only provides information if there is a network connection, but not if the network is connected to the Internet

Note that on Android, this does not guarantee connection to Internet. For instance, the app might have wifi access but it might be a VPN or a hotel WiFi with no access.

You can use

import 'dart:io';
...
try {
  final result = await InternetAddress.lookup('google.com');
  if (result.isNotEmpty && result[0].rawAddress.isNotEmpty) {
    print('connected');
  }
} on SocketException catch (_) {
  print('not connected');
}

I think that the best practice would be using connectivity plugin and wrapping your app in a stream builder

https://pub.dev/packages/connectivity

Your main screen / main page should be something like this:

class MainScreen extends StatelessWidget {

  Stream connectivityStream = Connectivity().onConnectivityChanged;
  
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: AppStyle.backgroundColor,
      body: StreamBuilder<ConnectivityResult>(
        stream: connectivityStream,
        builder: (context, snapshot) {
          if (snapshot.hasData) {
            final connectivityResult = snapshot.data;

            if (connectivityResult == ConnectivityResult.none) {
              return NoConnectionPage();
            }
            return HomePage();

          } else if (snapshot.hasError) {

            return NoConnectionPage(); 
            // or some error page, but I think no connection page is what you
            // want here
          } 

          return Center(child: CircularProgressIndicator());
        }
      )
    );
  }
}

In NoConnectionPage() you can have a button that retries the connection with a method like this:

void _retryConnection() async {
      try {
        final result = await InternetAddress.lookup('example.com');
      if (result.isNotEmpty && result[0].rawAddress.isNotEmpty) {
        print('connected');
        Navigator.of(context).pop(); // going back to MainScreen()
      }
    } on SocketException catch (_) {
      print('not connected');
    }
  }

Simply use the internet_connectivity_checker package like this:

class Hello extends StatelessWidget {
  const Hello({super.key});

  @override
  Widget build(BuildContext context) {
    return internetConnectivityBuilder(
      (status) {
        bool connected = status == ConnectivityStatus.online;
        return Text(connected ? "Online" : "Offline");
      },
    );
  }
}

Get more info about this package here .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM