Search code examples
androidiosflutterdartget

How to keep checking all the time for internet connection in flutter


I've got an android application that depends on the internet to work. I need to find a way to keep checking all the time for internet existence to view the application .. otherwise, when there is no internet I should view a widget that says no internet connection.

I have tried the package connectivity but it is not working as expected as it only checks for the switch ( wifi -mobile data ) if it is on or off, not real internet.

I thought sending a get request to a website and analyzing the response status code would be a good idea for me. so here is what I tried :

Check Connection Class

class CheckConnectionService {
  Future<bool> checkConnection() async {
    int theCode = 0;
    Client client = Client();
    try {
      await client.get('http://www.google.com').then((value) {
        theCode = value.statusCode;
      });
    }catch(e){
      print(e);
      return false;
    }finally{
      client.close();
    }
    if (theCode == 200){
      return true;
    }
    return false;
  }
}

then in my main.dart I've tried to use this check to be running all the time, here is my code:


class MyApp extends StatefulWidget {
  // This widget is the root of your application.
  @override
  _MyAppState createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
  bool internetExists = true;

  Stream checkIfOnline() async* {
    await CheckConnectionService().checkConnection().then((check) {
      print(check);
    if (check){
      internetExists = true;
      setState(() {});
    } else {
      internetExists = false;
      setState(() {});
    }
    });
  }
  @override
  Widget build(BuildContext context) {
    checkIfOnline();
    if (!internetExists){
        return MaterialApp(
          title: 'G-Attend',
          home: NoInternet(),
        );
    } else{
      return MaterialApp(
        theme: ThemeData(
          fontFamily: 'Anton',
          primaryColor: Hexcolor('#691b99'),
          primaryColorLight: Hexcolor('#9b4dcb'),
          primaryColorDark: Hexcolor('#37006a'),
          secondaryHeaderColor: Hexcolor('#60C0D5'),
          accentColor: Colors.deepOrange,
        ),
        initialRoute: '/splash',
        routes: {
          '/splash': (context) => SplashScreen(),
          '/login': (context) => Login(),
          '/index': (context) => Index(),
          '/settings': (context) => Settings(),
          '/requests': (context) => Requests(),
          '/add_request': (context) => AddRequest(),
          '/request_comments': (context) => RequestComments(),
        },
      );
    }
  }
}

What happens that it is always showing the part where the internet should be working, even when there is no real internet connection.


Solution

  • To check the internet connection you can use the package data_connection_checker:

    bool hasConnection = false;
    
    @override
    void initState() {
      super.initState();
    
      DataConnectionChecker().onStatusChange.listen((status) {
        setState(() {
          switch(status){
            case DataConnectionStatus.connected:
              hasConnection = true;
              break;
            case DataConnectionStatus.disconnected:
              hasConnection = false;
              break;
          }
        });
      });
    }
    

    I usually go to External Libraries > data_connection_checker-version

    And in the dart file i change the DEFAULT_INTERNAL to 1, for verification to happen every 1 second:

    static const Duration DEFAULT_INTERVAL = const Duration(seconds: 1);