简体   繁体   中英

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"? I've tried it with it doesn't seems good to me. Thanks in advance

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.
}
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');
}

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}

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