首页 > 解决方案 > Connectivity package's onConnectionChanged() being called multiple times

问题描述

I have setup a basic check using Connectivity's Readme on checking internet connectivity.

@override
  void initState() {
    super.initState();
    subscription = Connectivity()
        .onConnectivityChanged
        .listen((ConnectivityResult result) {
      // Got a new connectivity status!
      print("Check: $result");
    });

  }

  @override
  void dispose() {
    print("Disposing Connection ...");
    super.dispose();
    subscription.cancel();
  }

I haven't made any significant changes to the code itself. However, I when I checked the logs, It seems like the app is calling the function onConnectivityChanged() twice, everytime a change in connection occurs.

Here are the logs:

Restarted application in 1,611ms.
I/flutter (17481): Check: ConnectivityResult.none
I/flutter (17481): Check: ConnectivityResult.mobile
I/flutter (17481): Check: ConnectivityResult.mobile
I/flutter (17481): Check: ConnectivityResult.none
I/flutter (17481): Check: ConnectivityResult.none
I/flutter (17481): Check: ConnectivityResult.wifi
I/flutter (17481): Check: ConnectivityResult.wifi

The first result is ConnectivityResult.none and it appears only once. Because the app checks the connectivity only once when the current widget loads. However, after the first (correct) result, all the results are obtained twice, even though they should come out only once.

This has led to some complications in my app. Everytime I see a connection change, I show a dialog box to the user with the following options:

But since the check somehow runs twice on connection changes, I have been seeing two dialog boxes. Not only that, since when I pop the dialog box out of the context, the app loads once again and does the check on initState() causing the dialog box to show again. It will continue unless the phone is on WiFi, where there are no checks.

标签: androidflutterdartconnectivity

解决方案


推荐阅读