Home > Mobile >  Is there any way in flutter to check internet connectivity without using "provider"?
Is there any way in flutter to check internet connectivity without using "provider"?

Time:08-18

Is there any way in flutter to check internet connectivity without using "provider"? I've tried it with it doesn't seems good to me. Thanks in advance

CodePudding user response:

Use this package: https://pub.dev/packages/connectivity_plus

import 'package:connectivity_plus/connectivity_plus.dart';

var connectivityResult = await (Connectivity().checkConnectivity());
if (connectivityResult == ConnectivityResult.mobile) {
  // I am connected to a mobile network.
} else if (connectivityResult == ConnectivityResult.wifi) {
  // I am connected to a wifi network.
}

CodePudding user response:

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

Usages:

if(await checkNetwork()){
    print('connected to internet');
}
else{
    print('disconnect');
}

CodePudding user response:

Use This Package https://pub.dev/packages/connectivity_plus

initialize the Connectivity result with a none at start.

ConnectivityResult _connectionStatus = ConnectivityResult.none;
final Connectivity _connectivity = Connectivity();

for stream, if the internet connect/disconnect in the middle of the app.

 late StreamSubscription<ConnectivityResult> _connectivitySubscription;
            
    

Call that function from initstate

Future<void> initConnectivity() async {
        late ConnectivityResult result;
        try {
          result = await _connectivity.checkConnectivity();
        } on PlatformException catch (e) {
          print(e);
          return;
        }
        if (!mounted) {
          return Future.value(null);
        }
    
        return _updateConnectionStatus(result);
      }
    
_connectivitySubscription = _connectivity.onConnectivityChanged.listen(_updateConnectionStatus);
    
    if (_connectionStatus == ConnectivityResult.mobile ||_connectionStatus==ConnectivityResult.wifi) 
    {
internet is available
    }
    else{not available}
  • Related