E/EventChannel#plugins.flutter.io/connectivity_status(28677): 无法关闭现有事件流

huangapple go评论79阅读模式
英文:

E/EventChannel#plugins.flutter.io/connectivity_status(28677): Failed to close existing event stream

问题

我已经在Flutter中开始了开发。在一个场景中,我必须检查用户是否连接到互联网。我正在使用connectivity 0.4.9+5data_connection_checker 0.3.4来组合检查用户是否有活动连接。

我已经创建了一个名为internet_connectivity_service.dart的文件,该文件执行与此相关的所有任务。

class InternetConnectivityService {
  StreamSubscription<ConnectivityResult> _subscription;

  /*
   * 此函数检查设备是否具有互联网连接。
   * 借助DataConnectionChecker,它会检查实际的互联网连接。
   */
  Future<bool> _checkConnectivity() async {
    if (await DataConnectionChecker().hasConnection) {
      return true;
    } else {
      return false;
    }
  }

  /*
   * 每次连接更改请求时都会调用此函数。
   * 使用Connectivity软件包,它将检查连接和连接类型。
   * 此函数的返回类型为Future<bool>,它执行异步请求以检查连接。
   * 在检查连接类型之后,它会检查设备是否具有可访问的互联网。
   */
  Future<bool> _hasInternet() async {
    var connectivityResult = await (Connectivity().checkConnectivity());
    if (connectivityResult == ConnectivityResult.mobile) {
      return _checkConnectivity();
    } else if (connectivityResult == ConnectivityResult.wifi) {
      return _checkConnectivity();
    } else {
      return false;
    }
  }

  StreamSubscription<ConnectivityResult> initInterNetConnectivitySubscription(
      BuildContext context) {
    // * 订阅连接更改
    _subscription = Connectivity().onConnectivityChanged.listen(
      (ConnectivityResult result) {
        _hasInternet().then(
          (result) {
            // * 当断开互联网连接时
            Size size = MediaQuery.of(context).size;
            if (!result) {
              Scaffold.of(context).showSnackBar(
                snackBarBuilder(
                    color: kErrorColor,
                    text: '连接丢失',
                    context: context),
              );
            } else {
              Scaffold.of(context).showSnackBar(
                snackBarBuilder(
                    color: kSuccessColor, text: '已连接', context: context),
              );
            }
          },
        );
      },
    );
    return _subscription;
  }

  disposeSubscription() {
    _subscription.cancel();
  }
}

函数initInterNetConnectivitySubscriptiondisposeSubscription用于订阅和取消订阅特定事件。我从需要这个功能的组件中调用这些方法。

例如:

InternetConnectivityService internetConnectivityService =
    InternetConnectivityService();

@override
initState() {
  internetConnectivityService.initInterNetConnectivitySubscription(context);
  super.initState();
}

@override
dispose() {
  internetConnectivityService.disposeSubscription();
  super.dispose();
}

通过这样做,功能有时会正常工作,但有时我会遇到错误,错误消息为E/EventChannel#plugins.flutter.io/connectivity_status(28677): Failed to close existing event stream

完整的堆栈跟踪如下。

   Restarted application in 5,259ms.
E/EventChannel#plugins.flutter.io/connectivity_status(28677): Failed to close existing event stream
E/EventChannel#plugins.flutter.io/connectivity_status(28677): java.lang.IllegalArgumentException: NetworkCallback was not registered
... (以下是堆栈跟踪的其余部分)

由于这个错误,我的应用程序没有崩溃,但有时功能无法按预期工作。请告诉我是否犯了错误,或者是否有更好的方法来实现这一点。我只希望实现这样的功能,即当用户没有连接时,应用程序将显示消息,指示您未连接到互联网。

英文:

I have started development in flutter. In one scenario I have to check if the user is connected to internet or not. I am using connectivity 0.4.9+5 and data_connection_checker 0.3.4 in combination to check if user has active connection or not.

I have create one file internet_connectivity_service.dart which perform all the task related to it.

class InternetConnectivityService {
  StreamSubscription&lt;ConnectivityResult&gt; _subscription;

  /*
    * This function check if the device has internet connectivity.
    * With the help of DataConnectionChecker it checks for actual internet connectivity. 
  */
  Future&lt;bool&gt; _checkConnectivity() async {
    if (await DataConnectionChecker().hasConnection) {
      return true;
    } else {
      return false;
    }
  }

  /*
    * This function is invoked to on each connection change request.
    * Using Connectivity package it will check for connectivity and connection type.
    * This function has return type of Future&lt;bool&gt; which perform async request to check connectivity.
    * After checking connection type it check for divice has internet accesssible or not.
  */
  Future&lt;bool&gt; _hasInternet() async {
    var connectivityResult = await (Connectivity().checkConnectivity());
    if (connectivityResult == ConnectivityResult.mobile) {
      return _checkConnectivity();
    } else if (connectivityResult == ConnectivityResult.wifi) {
      return _checkConnectivity();
    } else {
      return false;
    }
  }

  StreamSubscription&lt;ConnectivityResult&gt; initInterNetConnectivitySubscription(
      BuildContext context) {
    // * Subscribe to connectivity changes
    _subscription = Connectivity().onConnectivityChanged.listen(
      (ConnectivityResult result) {
        _hasInternet().then(
          (result) {
            // * When internet is disconnected
            Size size = MediaQuery.of(context).size;
            if (!result) {
              Scaffold.of(context).showSnackBar(
                snackBarBuilder(
                    color: kErrorColor,
                    text: &#39;Connection Lost&#39;,
                    context: context),
              );
            } else {
              Scaffold.of(context).showSnackBar(
                snackBarBuilder(
                    color: kSuccessColor, text: &#39;Connected&#39;, context: context),
              );
            }
          },
        );
      },
    );
    return _subscription;
  }

  disposeSubscription() {
    _subscription.cancel();
  }
}

Function initInterNetConnectivitySubscription and disposeSubscription are used for subscribe and unsubscribe for particular event. I am calling these methods from component where I want this functionality.

For Example:

     InternetConnectivityService internetConnectivityService =
      InternetConnectivityService();

  @override
  initState() {
    internetConnectivityService.initInterNetConnectivitySubscription(context);
    super.initState();
  }

  @override
  dispose() {
    internetConnectivityService.disposeSubscription();
    super.dispose();
  }

By doing so functionality is working sometimes but sometimes I am facing error stating E/EventChannel#plugins.flutter.io/connectivity_status(28677): Failed to close existing event stream.

Complete stack trace.

   Restarted application in 5,259ms.
E/EventChannel#plugins.flutter.io/connectivity_status(28677): Failed to close existing event stream
E/EventChannel#plugins.flutter.io/connectivity_status(28677): java.lang.IllegalArgumentException: NetworkCallback was not registered
E/EventChannel#plugins.flutter.io/connectivity_status(28677): 	at com.android.internal.util.Preconditions.checkArgument(Preconditions.java:50)
E/EventChannel#plugins.flutter.io/connectivity_status(28677): 	at android.net.ConnectivityManager.unregisterNetworkCallback(ConnectivityManager.java:4009)
E/EventChannel#plugins.flutter.io/connectivity_status(28677): 	at io.flutter.plugins.connectivity.ConnectivityBroadcastReceiver.onCancel(ConnectivityBroadcastReceiver.java:53)
E/EventChannel#plugins.flutter.io/connectivity_status(28677): 	at io.flutter.plugin.common.EventChannel$IncomingStreamRequestHandler.onListen(EventChannel.java:182)
E/EventChannel#plugins.flutter.io/connectivity_status(28677): 	at io.flutter.plugin.common.EventChannel$IncomingStreamRequestHandler.onMessage(EventChannel.java:167)
E/EventChannel#plugins.flutter.io/connectivity_status(28677): 	at io.flutter.embedding.engine.dart.DartMessenger.handleMessageFromDart(DartMessenger.java:85)
E/EventChannel#plugins.flutter.io/connectivity_status(28677): 	at io.flutter.embedding.engine.FlutterJNI.handlePlatformMessage(FlutterJNI.java:692)
E/EventChannel#plugins.flutter.io/connectivity_status(28677): 	at android.os.MessageQueue.nativePollOnce(Native Method)
E/EventChannel#plugins.flutter.io/connectivity_status(28677): 	at android.os.MessageQueue.next(MessageQueue.java:336)
E/EventChannel#plugins.flutter.io/connectivity_status(28677): 	at android.os.Looper.loop(Looper.java:174)
E/EventChannel#plugins.flutter.io/connectivity_status(28677): 	at android.app.ActivityThread.main(ActivityThread.java:7356)
E/EventChannel#plugins.flutter.io/connectivity_status(28677): 	at java.lang.reflect.Method.invoke(Native Method)
E/EventChannel#plugins.flutter.io/connectivity_status(28677): 	at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:492)
E/EventChannel#plugins.flutter.io/connectivity_status(28677): 	at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:930)**strong text**

Due to this error my application is not getting crash but sometime functionality doesnot work as desired. Please let me know if I am making some mistake or if their is better way of doing so. I just wan't to have functionality in which when user don't have connection than application will show stating that you are not connected to internet.

答案1

得分: 6

我假设您已经解决了这个问题,所以这是给将来仍然遇到这个问题的人的提示。

我通过升级到最新版本来修复了这个问题,他们在最新版本中修复了这个问题:

connectivity: ^2.0.2
英文:

I assume you have already solved this problem so this if for the people who come in the future and still have this problem.

I fixed it by upgrading to the latest version where they fixed the issue:

connectivity: ^2.0.2

huangapple
  • 本文由 发表于 2020年10月17日 14:14:36
  • 转载请务必保留本文链接:https://go.coder-hub.com/64399547.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定