Home > Blockchain >  How to check the internet connection for each 5 second in flutter?
How to check the internet connection for each 5 second in flutter?

Time:08-06

I want to check the internet connection for my flutter app in the time interval of each 5 seconds.

CodePudding user response:

To check internet connection you can use dart:io like this:

import 'dart:io;'
Future<bool> checkInternetConection() async {
  try {
    final result = await InternetAddress.lookup('example.com');
    if (result.isNotEmpty && result[0].rawAddress.isNotEmpty) {
      return true;
    }
  } on SocketException catch (_) {
      return false;
  }
  return false;
}

Will return true if you have internet connection and false if not. Otherwise, could you be more specific about the interval of 5 sec?

CodePudding user response:

you can use Ariel Soriano Vassia answer with combination with Timer.periodic like this:

bool isConnected = false;
  Future<bool> checkInternetConnection() async {
    try {
      final result = await InternetAddress.lookup('example.com');
      if (result.isNotEmpty && result[0].rawAddress.isNotEmpty) {
        return true;
      }
    } on SocketException catch (_) {
      return false;
    }
    return false;
  }
  @override
  Widget build(BuildContext context) {
    Timer.periodic(const Duration(seconds: 5), (timer) {
      checkInternetConnection().then((value) {
        setState(() {
          isConnected = value;
          print(isConnected);
        });
      });
    });
    return Scaffold(...)
  • Related