检查Flutter应用程序上是否有可用的Internet连接

时间:2018-04-04 09:53:59

标签: dart flutter

我有一个要执行的网络电话。但在此之前,我需要检查设备是否具有互联网连接。

这是我到目前为止所做的:

  var connectivityResult = new Connectivity().checkConnectivity();// User defined class
    if (connectivityResult == ConnectivityResult.mobile ||
        connectivityResult == ConnectivityResult.wifi) {*/
    this.getData();
    } else {
      neverSatisfied();
    }

以上方法无效。

21 个答案:

答案 0 :(得分:40)

connectivity插件在其文档中声明,它仅在有网络连接时提供信息,但如果网络连接到Internet则不提供

  

请注意,在Android上,这并不能保证与Internet的连接。例如,该应用可能具有WiFi访问权限,但它可能是VPN或无法访问的酒店WiFi。

您可以使用

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

答案 1 :(得分:21)

我发现仅使用connectivity软件包还不足以判断互联网是否可用。在Android中,它仅检查是否有WIFI或是否打开了移动数据,而不检查实际的互联网连接。在我的测试过程中,即使没有移动信号,ConnectivityResult.mobile也会返回true。

通过IOS,我的测试发现,当手机没有信号时,连接插件可以正确检测是否存在互联网连接,问题仅出在Android上。

我发现的解决方案是将data_connection_checker软件包与连接软件包一起使用。只需向几个可靠的地址发出请求即可确保互联网连接,检查的默认超时时间约为10秒。

我完成的isInternet功能看起来像这样:

  Future<bool> isInternet() async {
    var connectivityResult = await (Connectivity().checkConnectivity());
    if (connectivityResult == ConnectivityResult.mobile) {
      // I am connected to a mobile network, make sure there is actually a net connection.
      if (await DataConnectionChecker().hasConnection) {
        // Mobile data detected & internet connection confirmed.
        return true;
      } else {
        // Mobile data detected but no internet connection found.
        return false;
      }
    } else if (connectivityResult == ConnectivityResult.wifi) {
      // I am connected to a WIFI network, make sure there is actually a net connection.
      if (await DataConnectionChecker().hasConnection) {
        // Wifi detected & internet connection confirmed.
        return true;
      } else {
        // Wifi detected but no internet connection found.
        return false;
      }
    } else {
      // Neither mobile data or WIFI detected, not internet connection found.
      return false;
    }
  }

if (await DataConnectionChecker().hasConnection)部分对于移动和wifi连接都是相同的,可能应该移至单独的功能。为了使内容更具可读性,我在这里没有这样做。

这是我的第一个Stack Overflow答案,希望它能对某人有所帮助。

答案 2 :(得分:15)

对于在此居住的其他人,我想补充一下GünterZöchbauer的答案,这是我的解决方案,用于实施实用程序以了解是否有Internet,无论是否存在其他任何东西。

免责声明:

我对Dart和Flutter都是陌生的,所以这可能不是最好的方法,但是希望获得反馈。


结合flutter_connectivity和GünterZöchbauer的连接测试

我的要求

我不想在检查连接的任何地方都使用一堆重复的代码,而是希望它能够在发生更改时自动更新组件或其他任何关心连接的内容。

ConnectionStatusSingleton

首先,我们设置一个Singleton。如果您不熟悉这种模式,则在线上有很多关于它们的好信息。但是要点是,您希望在应用程序生命周期中创建一个类的单个实例,并能够在任何地方使用它。

此单例挂接到flutter_connectivity并侦听连接更改,然后测试网络连接,然后使用StreamController更新所有需要的内容。

它看起来像这样:

import 'dart:io'; //InternetAddress utility
import 'dart:async'; //For StreamController/Stream

import 'package:connectivity/connectivity.dart';

class ConnectionStatusSingleton {
    //This creates the single instance by calling the `_internal` constructor specified below
    static final ConnectionStatusSingleton _singleton = new ConnectionStatusSingleton._internal();
    ConnectionStatusSingleton._internal();

    //This is what's used to retrieve the instance through the app
    static ConnectionStatusSingleton getInstance() => _singleton;

    //This tracks the current connection status
    bool hasConnection = false;

    //This is how we'll allow subscribing to connection changes
    StreamController connectionChangeController = new StreamController.broadcast();

    //flutter_connectivity
    final Connectivity _connectivity = Connectivity();

    //Hook into flutter_connectivity's Stream to listen for changes
    //And check the connection status out of the gate
    void initialize() {
        _connectivity.onConnectivityChanged.listen(_connectionChange);
        checkConnection();
    }

    Stream get connectionChange => connectionChangeController.stream;

    //A clean up method to close our StreamController
    //   Because this is meant to exist through the entire application life cycle this isn't
    //   really an issue
    void dispose() {
        connectionChangeController.close();
    }

    //flutter_connectivity's listener
    void _connectionChange(ConnectivityResult result) {
        checkConnection();
    }

    //The test to actually see if there is a connection
    Future<bool> checkConnection() async {
        bool previousConnection = hasConnection;

        try {
            final result = await InternetAddress.lookup('google.com');
            if (result.isNotEmpty && result[0].rawAddress.isNotEmpty) {
                hasConnection = true;
            } else {
                hasConnection = false;
            }
        } on SocketException catch(_) {
            hasConnection = false;
        }

        //The connection status changed send out an update to all listeners
        if (previousConnection != hasConnection) {
            connectionChangeController.add(hasConnection);
        }

        return hasConnection;
    }
}

用法

初始化

首先,我们必须确保调用单例的初始化。但是只有一次。 这取决于您,但我是在应用程序的main()中完成的:

void main() {
    ConnectionStatusSingleton connectionStatus = ConnectionStatusSingleton.getInstance();
    connectionStatus.initialize();

    runApp(MyApp());

    //Call this if initialization is occuring in a scope that will end during app lifecycle
    //connectionStatus.dispose();   
}

Widget或其他地方

import 'dart:async'; //For StreamSubscription

...

class MyWidgetState extends State<MyWidget> {
    StreamSubscription _connectionChangeStream;

    bool isOffline = false;

    @override
    initState() {
        super.initState();

        ConnectionStatusSingleton connectionStatus = ConnectionStatusSingleton.getInstance();
        _connectionChangeStream = connectionStatus.connectionChange.listen(connectionChanged);
    }

    void connectionChanged(dynamic hasConnection) {
        setState(() {
            isOffline = !hasConnection;
        });
    }

    @override
    Widget build(BuildContext ctxt) {
        ...
    }
}

希望其他人觉得这有用!


示例GitHub存储库:https://github.com/dennmat/flutter-connectiontest-example

在模拟器中切换飞行模式以查看结果

答案 3 :(得分:3)

好吧,我几乎阅读了所有帖子,@dennmat 帖子对我最有用。虽然它对我不起作用,而且也已经过时了。我已经更新了 Flutter 更新的 connectivity 包(即 connectivity_plus)和 data_connection_checker(检查移动设备和 wifi 是否有实际的互联网连接)。
在这篇文章之后,您将能够持续监听互联网连接。

1.添加依赖
a) connectivity_plus: ^1.0.6
b) data_connection_checker: ^0.3.4

2.处理所有连接的自定义类。

import 'dart:async';
import 'package:connectivity_plus/connectivity_plus.dart';
import 'package:data_connection_checker/data_connection_checker.dart'; 

class ConnectionUtil {
  //This creates the single instance by calling the `_internal` constructor specified below
  static final ConnectionUtil _singleton = new ConnectionUtil._internal();
  ConnectionUtil._internal();
  //This is what's used to retrieve the instance through the app
  static ConnectionUtil getInstance() => _singleton;
  //This tracks the current connection status
  bool hasConnection = false;
  //This is how we'll allow subscribing to connection changes
  StreamController connectionChangeController = StreamController();
  //flutter_connectivity
  final Connectivity _connectivity = Connectivity();
  void initialize() {
    _connectivity.onConnectivityChanged.listen(_connectionChange);
  }
  //flutter_connectivity's listener
  void _connectionChange(ConnectivityResult result) {
    hasInternetInternetConnection();
  }
  Stream get connectionChange => connectionChangeController.stream;
  Future<bool> hasInternetInternetConnection() async {
    bool previousConnection = hasConnection;
    var connectivityResult = await (Connectivity().checkConnectivity());
    //Check if device is just connect with mobile network or wifi
    if (connectivityResult == ConnectivityResult.mobile ||
        connectivityResult == ConnectivityResult.wifi) {
      //Check there is actual internet connection with a mobile network or wifi
      if (await DataConnectionChecker().hasConnection) {
        // Network data detected & internet connection confirmed.
        hasConnection = true;
      } else {
        // Network data detected but no internet connection found.
        hasConnection = false;
      }
    }
    // device has no mobile network and wifi connection at all
    else {
      hasConnection = false;
    }
    // The connection status changed send out an update to all listeners
    if (previousConnection != hasConnection) {
      connectionChangeController.add(hasConnection);
    }
    return hasConnection;
  }
}
  1. 在任何地方检查连接并监听变化。
@override
  initState() {
    print('called');
    //Create instance
    ConnectionUtil connectionStatus = ConnectionUtil.getInstance();
    //Initialize
    connectionStatus.initialize();
    //Listen for connection change
    _connectionChangeStream = connectionStatus.connectionChange.listen((event) {
      print(event);
    });

    super.initState();
  }

现在在切换飞行模式时检查日志。你应该得到带有 true 和 false 值的日志。

注意:这在 flutter web 中不起作用,如果您希望使其工作而不是使用 diohttp 插件而不是 data_connection_checker

示例项目可以在 here 中找到。谢谢

答案 4 :(得分:3)

使用

dependencies:
  connectivity: ^0.4.2

我们从resouces那里得到的是

      import 'package:connectivity/connectivity.dart';

      Future<bool> check() async {
        var connectivityResult = await (Connectivity().checkConnectivity());
        if (connectivityResult == ConnectivityResult.mobile) {
          return true;
        } else if (connectivityResult == ConnectivityResult.wifi) {
          return true;
        }
        return false;
      }

对于我来说,未来没什么大问题,我们必须像这样:

check().then((intenet) {
      if (intenet != null && intenet) {
        // Internet Present Case
      }
      // No-Internet Case
    });

因此,为了解决此问题,我创建了一个类,该类接受带有布尔型isNetworkPresent参数的函数,例如

methodName(bool isNetworkPresent){}

实用程序类为

import 'package:connectivity/connectivity.dart';

class NetworkCheck {
  Future<bool> check() async {
    var connectivityResult = await (Connectivity().checkConnectivity());
    if (connectivityResult == ConnectivityResult.mobile) {
      return true;
    } else if (connectivityResult == ConnectivityResult.wifi) {
      return true;
    }
    return false;
  }

  dynamic checkInternet(Function func) {
    check().then((intenet) {
      if (intenet != null && intenet) {
        func(true);
      }
      else{
    func(false);
  }
    });
  }
}

并使用连通性检查实用程序

  fetchPrefrence(bool isNetworkPresent) {
    if(isNetworkPresent){

    }else{

    }
  }

我将使用这种语法

NetworkCheck networkCheck = new NetworkCheck();
networkCheck.checkInternet(fetchPrefrence)

答案 5 :(得分:1)

我为小部件状态创建了基类

使用State<LoginPage>代替BaseState<LoginPage> 然后只需使用布尔变量isOnline

Text(isOnline ? 'is Online' : 'is Offline')

首先,添加连接插件:

dependencies:
  connectivity: ^0.4.3+2

然后添加BaseState类

import 'dart:async';
import 'dart:io';
import 'package:flutter/services.dart';

import 'package:connectivity/connectivity.dart';
import 'package:flutter/widgets.dart';

/// a base class for any statful widget for checking internet connectivity
abstract class BaseState<T extends StatefulWidget> extends State {
  final Connectivity _connectivity = Connectivity();

  StreamSubscription<ConnectivityResult> _connectivitySubscription;

  /// the internet connectivity status
  bool isOnline = true;

  /// initialize connectivity checking
  /// Platform messages are asynchronous, so we initialize in an async method.
  Future<void> initConnectivity() async {
    // Platform messages may fail, so we use a try/catch PlatformException.
    try {
      await _connectivity.checkConnectivity();
    } on PlatformException catch (e) {
      print(e.toString());
    }

    // If the widget was removed from the tree while the asynchronous platform
    // message was in flight, we want to discard the reply rather than calling
    // setState to update our non-existent appearance.
    if (!mounted) {
      return;
    }

    await _updateConnectionStatus().then((bool isConnected) => setState(() {
          isOnline = isConnected;
        }));
  }

  @override
  void initState() {
    super.initState();
    initConnectivity();
    _connectivitySubscription = Connectivity()
        .onConnectivityChanged
        .listen((ConnectivityResult result) async {
      await _updateConnectionStatus().then((bool isConnected) => setState(() {
            isOnline = isConnected;
          }));
    });
  }

  @override
  void dispose() {
    _connectivitySubscription.cancel();
    super.dispose();
  }

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

答案 6 :(得分:1)

连接性:包不能保证实际的互联网连接 (可能只是没有网络的wifi连接)。

文档引用:

  

请注意,在Android上,这不保证可以连接到Internet。例如,该应用可能可以访问wifi,但可能是VPN或无法访问的酒店WiFi。

如果您确实需要检查与www Internet的连接,最好的选择是

data_connection_checker package

答案 7 :(得分:1)

使用connectivity_widget: ^0.1.7

添加依赖项:

dependencies:
     connectivity_widget: ^0.1.7

添加代码:

           ConnectivityWidget(
            builder: (context, isOnline) => Center(
              child: Column(
                mainAxisAlignment: MainAxisAlignment.center,
                children: <Widget>[
                  Text(
                    "${isOnline ? 'Connected' : 'Offline'}",
                    style: TextStyle(
                        fontSize: 30,
                        color: isOnline ? Colors.green : Colors.red),
                  ),
                ],
              ),
            ),
          )

输出:

enter image description here

答案 8 :(得分:1)

这是我的解决方案,它可以检查Internet连接以及数据连接,我希望您喜欢它。

首先在pubsec.yaml中添加依赖项
dependencies:        
    data_connection_checker:
这是我的解决方案的main.dart
import 'dart:async';

import 'package:data_connection_checker/data_connection_checker.dart';
import 'package:flutter/material.dart';

void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: "Data Connection Checker",
      home: HomePage(),
    );
  }
}

class HomePage extends StatefulWidget {
  @override
  _HomePageState createState() => _HomePageState();
}

class _HomePageState extends State<HomePage> {
  StreamSubscription<DataConnectionStatus> listener;

  var Internetstatus = "Unknown";

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
//    _updateConnectionStatus();
      CheckInternet();
  }

  @override
  void dispose() {
    // TODO: implement dispose
    listener.cancel();
    super.dispose();
  }

  CheckInternet() async {
    // Simple check to see if we have internet
    print("The statement 'this machine is connected to the Internet' is: ");
    print(await DataConnectionChecker().hasConnection);
    // returns a bool

    // We can also get an enum instead of a bool
    print("Current status: ${await DataConnectionChecker().connectionStatus}");
    // prints either DataConnectionStatus.connected
    // or DataConnectionStatus.disconnected

    // This returns the last results from the last call
    // to either hasConnection or connectionStatus
    print("Last results: ${DataConnectionChecker().lastTryResults}");

    // actively listen for status updates
    listener = DataConnectionChecker().onStatusChange.listen((status) {
      switch (status) {
        case DataConnectionStatus.connected:
          Internetstatus="Connectd TO THe Internet";
          print('Data connection is available.');
          setState(() {

          });
          break;
        case DataConnectionStatus.disconnected:
          Internetstatus="No Data Connection";
          print('You are disconnected from the internet.');
          setState(() {

          });
          break;
      }
    });

    // close listener after 30 seconds, so the program doesn't run forever
//    await Future.delayed(Duration(seconds: 30));
//    await listener.cancel();
    return await await DataConnectionChecker().connectionStatus;
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text("Data Connection Checker"),
      ),
      body: Container(
        child: Center(
          child: Text("$Internetstatus"),
        ),
      ),
    );
  }
}

答案 9 :(得分:1)

我最终(尽管勉强)决定了@abernee在previous answer中针对此问题提供的解决方案。我总是尝试在项目中使用尽可能少的外部软件包-因为我知道外部软件包是我创建的软件中唯一[潜在的]故障点。因此,链接到两个外部软件包只是为了一个简单的实现,对我来说不容易

尽管如此,我还是采用了abernee的代码并对其进行了修改,以使其更简洁,更明智。明智的意思是,他在功能中消耗Connectivity package的功能,但随后通过不返回此程序包中最有价值的输出(即网络标识)而在内部浪费了它。这是abernee解决方案的修改版本:

import 'package:connectivity/connectivity.dart';
import 'package:data_connection_checker/data_connection_checker.dart';


// 'McGyver' - the ultimate cool guy (the best helper class any app can ask for).
class McGyver {

  static Future<Map<String, dynamic>> checkInternetAccess() async {
    //* ////////////////////////////////////////////////////////////////////////////////////////// *//
    //*   INFO: ONLY TWO return TYPES for Map 'dynamic' value => <bool> and <ConnectivityResult>   *//
    //* ////////////////////////////////////////////////////////////////////////////////////////// *//
    Map<String, dynamic> mapCon;
    final String isConn = 'isConnected', netType = 'networkType';
    ConnectivityResult conRes = await (Connectivity().checkConnectivity());
    switch (conRes) {
      case ConnectivityResult.wifi:   //* WiFi Network: true !!
        if (await DataConnectionChecker().hasConnection) {   //* Internet Access: true !!
          mapCon = Map.unmodifiable({isConn: true, netType: ConnectivityResult.wifi});
        } else {
          mapCon = Map.unmodifiable({isConn: false, netType: ConnectivityResult.wifi});
        }
        break;
      case ConnectivityResult.mobile:   //* Mobile Network: true !!
        if (await DataConnectionChecker().hasConnection) {   //* Internet Access: true !!
          mapCon = Map.unmodifiable({isConn: true, netType: ConnectivityResult.mobile});
        } else {
          mapCon = Map.unmodifiable({isConn: false, netType: ConnectivityResult.mobile});
        }
        break;
      case ConnectivityResult.none:   //* No Network: true !!
        mapCon = Map.unmodifiable({isConn: false, netType: ConnectivityResult.none});
        break;
    }
    return mapCon;
  }

}

然后,您可以通过在代码中的任何位置进行简单调用来使用此静态函数,如下所示:

bool isConn; ConnectivityResult netType;
McGyver.checkInternetAccess().then(
  (mapCIA) {  //* 'mapCIA' == amalgamation for 'map' from 'CheckInternetAccess' function result.
    debugPrint("'mapCIA' Keys: ${mapCIA.keys}");
    isConn = mapCIA['isConnected'];
    netType = mapCIA['networkType'];
  }
);
debugPrint("Internet Access: $isConn   |   Network Type: $netType");

很遗憾,您必须链接到两个外部程序包,以便在Flutter项目中获得非常强大的基本功能-但我想现在这是我们最好的有。与Data Connection Checker软件包相比,我实际上更喜欢Connectivity软件包-但是(在发布此消息时)前者缺少我需要的非常重要的网络识别功能连接软件包。这就是我[默认]默认使用此方法的原因。

答案 10 :(得分:1)

我对所提出的解决方案有疑问,使用lookup并不总是返回期望值。

这是由于DNS缓存所致,因此缓存了该调用的值,并且打算在下次尝试返回回缓存的值时进行一次正确的调用。当然,这是一个问题,因为这意味着如果您失去连接并呼叫lookup,它仍然可以像返回Internet一样返回缓存的值,反之,如果您在lookup返回null之后重新连接了Internet,即使在您确实有互联网连接的情况下,它在缓存持续时间内仍会返回几分钟的状态下仍然返回null。

TL; DR:lookup返回某项并不一定意味着您具有互联网,也没有返回任何信息并不一定意味着您没有互联网。这不可靠。

我从data_connection_checker插件中汲取了灵感,实现了以下解决方案:

 /// If any of the pings returns true then you have internet (for sure). If none do, you probably don't.
  Future<bool> _checkInternetAccess() {
    /// We use a mix of IPV4 and IPV6 here in case some networks only accept one of the types.
    /// Only tested with an IPV4 only network so far (I don't have access to an IPV6 network).
    final List<InternetAddress> dnss = [
      InternetAddress('8.8.8.8', type: InternetAddressType.IPv4), // Google
      InternetAddress('2001:4860:4860::8888', type: InternetAddressType.IPv6), // Google
      InternetAddress('1.1.1.1', type: InternetAddressType.IPv4), // CloudFlare
      InternetAddress('2606:4700:4700::1111', type: InternetAddressType.IPv6), // CloudFlare
      InternetAddress('208.67.222.222', type: InternetAddressType.IPv4), // OpenDNS
      InternetAddress('2620:0:ccc::2', type: InternetAddressType.IPv6), // OpenDNS
      InternetAddress('180.76.76.76', type: InternetAddressType.IPv4), // Baidu
      InternetAddress('2400:da00::6666', type: InternetAddressType.IPv6), // Baidu
    ];

    final Completer<bool> completer = Completer<bool>();

    int callsReturned = 0;
    void onCallReturned(bool isAlive) {
      if (completer.isCompleted) return;

      if (isAlive) {
        completer.complete(true);
      } else {
        callsReturned++;
        if (callsReturned >= dnss.length) {
          completer.complete(false);
        }
      }
    }

    dnss.forEach((dns) => _pingDns(dns).then(onCallReturned));

    return completer.future;
  }

  Future<bool> _pingDns(InternetAddress dnsAddress) async {
    const int dnsPort = 53;
    const Duration timeout = Duration(seconds: 3);

    Socket socket;
    try {
      socket = await Socket.connect(dnsAddress, dnsPort, timeout: timeout);
      socket?.destroy();
      return true;
    } on SocketException {
      socket?.destroy();
    }
    return false;
  }

_checkInternetAccess的调用最多需要timeout的时间才能完成(此处为3秒),如果我们可以访问任何DNS,则在第一个DNS到达后即会完成,而无需等待其他人(因为接触一个人就足以知道您有互联网)。对_pingDns的所有调用都是并行进行的。

它似乎可以在IPV4网络上很好地工作,当我不能在IPV6网络上对其进行测试(我无法访问它)时,我认为它应该仍然可以工作。它也适用于发布模式版本,但我还必须将我的应用提交给Apple,以查看他们是否发现此解决方案有任何问题。

它也应在大多数国家(包括中国)中运行,如果不能在一个国家中运行,则可以将DNS添加到目标国家/地区可以访问的列表中。

答案 11 :(得分:0)

基于这个答案https://stackoverflow.com/a/68436867/10761151

如果你使用了 dart null 安全,你会得到一个错误, 所以你可以更新依赖项data_connection_checker: ^0.3.4internet_connection_checker: ^0.0.1+2

你可以使用这个代码

public String getTextDefinition(String text){
    String definition = "";

    Word word = new Word(text);
    text = word.getText(); // update text to use the lower-case standardization of Word

    if(this.containsValue(text) == true){
        this.get(word);
        definition = word.toString();
    }

    if(this.containsValue(text) == false){
            Word mappedWord = get(text);
            if (mappedWord != null) {
                definition = mappedWord.toString();
            } else {
                definition = word.toString();
            }
    }

    return definition;
} 

在有状态小部件上,您可以实现此代码

import 'dart:async';
import 'package:connectivity_plus/connectivity_plus.dart';
import 'package:internet_connection_checker/internet_connection_checker.dart';

class ConnectionUtil {
  static final ConnectionUtil _singleton = new ConnectionUtil._internal();
  ConnectionUtil._internal();

  static ConnectionUtil getInstance() => _singleton;

  bool hasConnection = false;

  StreamController connectionChangeController = StreamController();

  final Connectivity _connectivity = Connectivity();
  void initialize() {
    _connectivity.onConnectivityChanged.listen(_connectionChange);
  }

  void _connectionChange(ConnectivityResult result) {
    _hasInternetInternetConnection();
  }

  Stream get connectionChange => connectionChangeController.stream;
  Future<bool> _hasInternetInternetConnection() async {
    bool previousConnection = hasConnection;
    var connectivityResult = await (Connectivity().checkConnectivity());
    if (connectivityResult == ConnectivityResult.mobile || connectivityResult == ConnectivityResult.wifi) {
      // this is the different
      if (await InternetConnectionChecker().hasConnection) {
        hasConnection = true;
      } else {
        hasConnection = false;
      }
    } else {
      hasConnection = false;
    }

    if (previousConnection != hasConnection) {
      connectionChangeController.add(hasConnection);
    }
    return hasConnection;
  }
}

答案 12 :(得分:0)

在@dennmatt的answer之后,我注意到InternetAddress.lookup可能会返回成功的结果,即使互联网连接已关闭-我通过从模拟器连接到家庭WiFi进行测试,然后断开连接我路由器的电缆。我认为原因是路由器会缓存域查找结果,因此不必在每个查找请求上查询DNS服务器。

无论如何,如果像我一样使用Firestore,则可以用空事务替换try-SocketException-catch块并捕获TimeoutExceptions:

try {
  await Firestore.instance.runTransaction((Transaction tx) {}).timeout(Duration(seconds: 5));
  hasConnection = true;
} on PlatformException catch(_) { // May be thrown on Airplane mode
  hasConnection = false;
} on TimeoutException catch(_) {
  hasConnection = false;
}

另外,请注意,previousConnection是在异步intenet-check之前设置的,因此从理论上讲,如果在短时间内多次调用checkConnection(),则在同一时间可能会有多个hasConnection=true行或连续多个hasConnection=false。 我不确定@dennmatt是否故意这样做,但在我们的用例中没有副作用(setState仅被调用两次且具有相同的值)。

答案 13 :(得分:0)

import 'dart:async';
import 'dart:io';
import 'package:flutter/material.dart';
import 'package:app_settings/app_settings.dart';
import 'package:connectivity/connectivity.dart';

class InternetConnect extends StatefulWidget {
  @override
  InternetConnectState createState() => InternetConnectState();
}

class InternetConnectState extends State<InternetConnect> {
  ConnectivityResult previous;
  bool dialogshown = false;
  StreamSubscription connectivitySubscription;

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

  void checkInternetConnect(BuildContext context) {
    connectivitySubscription = Connectivity()
        .onConnectivityChanged
        .listen((ConnectivityResult connresult) {
      if (connresult == ConnectivityResult.none) {
        dialogshown = true;
        showDialog(
            context: context, barrierDismissible: false, child: alertDialog());
      } else if (previous == ConnectivityResult.none) {
        checkinternet().then((result) {
          if (result == true) {
            if (dialogshown == true) {
              dialogshown = false;
              Navigator.pop(context);
            }
          }
        });
      }

      previous = connresult;
    });
  }

  AlertDialog alertDialog() {
    return AlertDialog(
      title: Text('ERROR'),
      content: Text("No Internet Detected."),
      actions: <Widget>[
        FlatButton(
          // method to exit application programitacally

          onPressed: () {
            AppSettings.openWIFISettings();
          },
          child: Text("Settings"),
        ),
      ],
    );
  }

  @override
  Widget build(BuildContext context) {
    return Container();
  }
}

    and you can use this method in init of any class

@override
void initState() {
  // TODO: implement initState
  InternetConnectState().checkInternetConnect(context);
  super.initState();
}

答案 14 :(得分:0)

对我来说,我只是在 Firebase 中创建一个数据并使用 future builder 来等待数据。在这里,像这样,您可以检查连接是否太慢,以便加载数据:

FutureBuilder(
    future: _getImage(context),
    builder: (context, snapshot) {
      switch (snapshot.connectionState) {
        case ConnectionState.none:
          return Text('Press button to start.');
        case ConnectionState.active:
        case ConnectionState.waiting:
          return Container(
              height:
                  MediaQuery.of(context).size.height / 1.25,
              width:
                  MediaQuery.of(context).size.width / 1.25,
              child: Loading());
        case ConnectionState.done:
          if (snapshot.hasData) {
            return snapshot.data;
          } else {
            return FlatButton(
              onPressed: () {
                Navigator.push(
                    context,
                    MaterialPageRoute(
                        builder: (context) =>
                            ProfilePage()));
              },
              child: Icon(
                Icons.add_a_photo,
                size: 50,
              ),
            );
          }
        // You can reach your snapshot.data['url'] in here
      }
      return null;
    },
  ),

答案 15 :(得分:0)

我接受的答案有些问题,但似乎可以解决其他问题。我想要一个可以从其使用的URL获得响应的解决方案,因此我认为http对于该功能非常有用,为此,我发现此答案确实很有帮助。 How do I check Internet Connectivity using HTTP requests(Flutter/Dart)?

答案 16 :(得分:0)

我使用data_connection_checker程序包检查了互联网访问,即使wifi或移动设备可以使用此连接,它也可以正常运行: 这是检查连接的代码:

bool result = await DataConnectionChecker().hasConnection;
if(result == true) {
   print('YAY! Free cute dog pics!');
} else {
   print('No internet :( Reason:');
   print(DataConnectionChecker().lastTryResults);
}

如果需要更多信息,请直接查看包装。 Data Connection Checker Package

答案 17 :(得分:0)

晚回答,但使用此软件包进行检查。 软件包名称:data_connection_checker

在您的pubspec.yuml文件中:

dependencies:
    data_connection_checker: ^0.3.4

创建一个名为connection.dart的文件或您想要的任何名称。 导入软件包:

import 'package:data_connection_checker/data_connection_checker.dart';

检查是否可以连接互联网:

print(await DataConnectionChecker().hasConnection);

答案 18 :(得分:0)

只需尝试使用Flutter中的Connectivity软件包简化代码即可。

import 'package:connectivity/connectivity.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.
} else {
  // I am not connected to the internet
}

答案 19 :(得分:0)

enter image description here

完整的示例,演示了Internet连接及其源的侦听器。

信用:connectivity和GünterZöchbauer

import 'dart:async';
import 'dart:io';
import 'package:connectivity/connectivity.dart';
import 'package:flutter/material.dart';

void main() => runApp(MaterialApp(home: HomePage()));

class HomePage extends StatefulWidget {
  @override
  _HomePageState createState() => _HomePageState();
}

class _HomePageState extends State<HomePage> {
  Map _source = {ConnectivityResult.none: false};
  MyConnectivity _connectivity = MyConnectivity.instance;

  @override
  void initState() {
    super.initState();
    _connectivity.initialise();
    _connectivity.myStream.listen((source) {
      setState(() => _source = source);
    });
  }

  @override
  Widget build(BuildContext context) {
    String string;
    switch (_source.keys.toList()[0]) {
      case ConnectivityResult.none:
        string = "Offline";
        break;
      case ConnectivityResult.mobile:
        string = "Mobile: Online";
        break;
      case ConnectivityResult.wifi:
        string = "WiFi: Online";
    }

    return Scaffold(
      appBar: AppBar(title: Text("Internet")),
      body: Center(child: Text("$string", style: TextStyle(fontSize: 36))),
    );
  }

  @override
  void dispose() {
    _connectivity.disposeStream();
    super.dispose();
  }
}

class MyConnectivity {
  MyConnectivity._internal();

  static final MyConnectivity _instance = MyConnectivity._internal();

  static MyConnectivity get instance => _instance;

  Connectivity connectivity = Connectivity();

  StreamController controller = StreamController.broadcast();

  Stream get myStream => controller.stream;

  void initialise() async {
    ConnectivityResult result = await connectivity.checkConnectivity();
    _checkStatus(result);
    connectivity.onConnectivityChanged.listen((result) {
      _checkStatus(result);
    });
  }

  void _checkStatus(ConnectivityResult result) async {
    bool isOnline = false;
    try {
      final result = await InternetAddress.lookup('example.com');
      if (result.isNotEmpty && result[0].rawAddress.isNotEmpty) {
        isOnline = true;
      } else
        isOnline = false;
    } on SocketException catch (_) {
      isOnline = false;
    }
    controller.sink.add({result: isOnline});
  }

  void disposeStream() => controller.close();
}

答案 20 :(得分:0)

想在@Oren's答案中添加一些内容:您确实应该再添加一个catch,它将捕获所有其他异常(为了安全起见),或者只是完全删除异常类型并使用一个catch来处理所有例外:

情况1:

try {
  await Firestore.instance
    .runTransaction((Transaction tx) {})
    .timeout(Duration(seconds: 5));
  hasConnection = true;
} on PlatformException catch(_) { // May be thrown on Airplane mode
  hasConnection = false;
} on TimeoutException catch(_) {
  hasConnection = false;
} catch (_) {
  hasConnection = false;
}

或更简单...

情况2:


try {
  await Firestore.instance
    .runTransaction((Transaction tx) {})
    .timeout(Duration(seconds: 5));
  hasConnection = true;
} catch (_) {
  hasConnection = false;
}