Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[Bug]: onConnectivityChanged callback not invoked when changing wifi network via settings (app is backgrounded) #3248

Open
8 tasks done
mposch-Z opened this issue Sep 9, 2024 · 4 comments
Labels
bug Something isn't working triage

Comments

@mposch-Z
Copy link

mposch-Z commented Sep 9, 2024

Platform

iOS v17.5.1

Plugin

connectivity_plus

Version

6.0.3+

Flutter SDK

3.19.1

Steps to reproduce

  1. Start sample application with WIFI in a connected state (connected to Wifi network A)
  2. Switch to mobile device settings-> Wi-fi -> and connect to a new Wifi network (now connected to Wifi network B). Ensure the connection is successful prior to navigating back to sample application.
  3. onConnectivityChanged callback will not be invoked

I've edited the pub cached version of the plugin during testing and the issue appears to have been introduced via the connectivity_plus.dart implementation change:
Stream<List> get onConnectivityChanged {
return _platform.onConnectivityChanged.distinct((a,b) => a.equals(b));
}

[MERGE] (https://github.com/fluttercommunity/plus_plugins/pull/2836/files)

In my investigation I noticed upon the app starting, the value of the list of connectivityResults is ConnectivityResult.wifi.
When changing the wifi network in the background, upon resuming the app the list of results again is reported as ConnectivityResult.wifi and is being filtered by the addition of the distinct operation on the stream. The act of changing the network in the background seems to omit the reporting of ConnectivityResult.none, which in turn, results in the omission of the following ConnectivityResult.wifi event coming across the stream for the wifi network change as the contents of the list have not changed.

NOTE 1: The issue is only reproducible on the release build of the app (not debug or profile mode).
NOTE 2: The issue does not occur if using the "Control Center" wifi selector. In this case, leave the app in the foreground but swipe from the upper right hand corner to open the control center...
NOTE 3: Reproduced on a physical device, not a simulator

Code Sample

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

void main() {
  runApp(const MyApp());
}

class MyApp extends StatelessWidget {
  const MyApp({super.key});
  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        // This is the theme of your application.
        //
        // TRY THIS: Try running your application with "flutter run". You'll see
        // the application has a purple toolbar. Then, without quitting the app,
        // try changing the seedColor in the colorScheme below to Colors.green
        // and then invoke "hot reload" (save your changes or press the "hot
        // reload" button in a Flutter-supported IDE, or press "r" if you used
        // the command line to start the app).
        //
        // Notice that the counter didn't reset back to zero; the application
        // state is not lost during the reload. To reset the state, use hot
        // restart instead.
        //
        // This works for code too, not just values: Most code changes can be
        // tested with just a hot reload.
        colorScheme: ColorScheme.fromSeed(seedColor: Colors.deepPurple),
        useMaterial3: true,
      ),
      home: const MyHomePage(title: 'Flutter Demo Home Page'),
    );
  }
}

class MyHomePage extends StatefulWidget {
  const MyHomePage({super.key, required this.title});

  // This widget is the home page of your application. It is stateful, meaning
  // that it has a State object (defined below) that contains fields that affect
  // how it looks.

  // This class is the configuration for the state. It holds the values (in this
  // case the title) provided by the parent (in this case the App widget) and
  // used by the build method of the State. Fields in a Widget subclass are
  // always marked "final".

  final String title;

  @override
  State<MyHomePage> createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  int _counter = 0;

  @override
  void initState() {
    Connectivity().onConnectivityChanged.listen((event) {
      print('onConnectivityChanged invoked: $event');
    });
  }

  void _incrementCounter() {
    setState(() {
      // This call to setState tells the Flutter framework that something has
      // changed in this State, which causes it to rerun the build method below
      // so that the display can reflect the updated values. If we changed
      // _counter without calling setState(), then the build method would not be
      // called again, and so nothing would appear to happen.
      _counter++;
    });
  }

  @override
  Widget build(BuildContext context) {
    // This method is rerun every time setState is called, for instance as done
    // by the _incrementCounter method above.
    //
    // The Flutter framework has been optimized to make rerunning build methods
    // fast, so that you can just rebuild anything that needs updating rather
    // than having to individually change instances of widgets.
    return Scaffold(
      appBar: AppBar(
        // TRY THIS: Try changing the color here to a specific color (to
        // Colors.amber, perhaps?) and trigger a hot reload to see the AppBar
        // change color while the other colors stay the same.
        backgroundColor: Theme.of(context).colorScheme.inversePrimary,
        // Here we take the value from the MyHomePage object that was created by
        // the App.build method, and use it to set our appbar title.
        title: Text(widget.title),
      ),
      body: Center(
        // Center is a layout widget. It takes a single child and positions it
        // in the middle of the parent.
        child: Column(
          // Column is also a layout widget. It takes a list of children and
          // arranges them vertically. By default, it sizes itself to fit its
          // children horizontally, and tries to be as tall as its parent.
          //
          // Column has various properties to control how it sizes itself and
          // how it positions its children. Here we use mainAxisAlignment to
          // center the children vertically; the main axis here is the vertical
          // axis because Columns are vertical (the cross axis would be
          // horizontal).
          //
          // TRY THIS: Invoke "debug painting" (choose the "Toggle Debug Paint"
          // action in the IDE, or press "p" in the console), to see the
          // wireframe for each widget.
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            const Text(
              'You have pushed the button this many times:',
            ),
            Text(
              '$_counter',
              style: Theme.of(context).textTheme.headlineMedium,
            ),
          ],
        ),
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: _incrementCounter,
        tooltip: 'Increment',
        child: const Icon(Icons.add),
      ), // This trailing comma makes auto-formatting nicer for build methods.
    );
  }
}

Logs

I am not seeing any backtick ('`') characters in this log output, and I am hesitant to include the full details as I would have to omit potentially personally identifiable information (dev cert ID/paths containing name info, etc..)

Kindly let me know what information is relevant and I will work to provide it.  The information likely won't prove useful in reproduction of the issue. 

DebugLogs:
[   +2 ms] Installing and launching... (completed in 3.7s)
[   +2 ms] Application running.
[   +2 ms] Flutter run key commands.
[   +1 ms] h List all available interactive commands.
[        ] c Clear the screen
[        ] q Quit (terminate the application on the device).
[  +69 ms] [ERROR:flutter/shell/platform/darwin/graphics/FlutterDarwinContextMetalImpeller.mm(42)] Using the Impeller rendering backend.
[  +21 ms] flutter: onConnectivityChanged invoked: [ConnectivityResult.wifi]
[+51141 ms] Application finished.
[   +1 ms] ensureAnalyticsSent: 0ms
[        ] Running 1 shutdown hook
[        ] Shutdown hooks complete
[   +2 ms] "flutter run" took 99,648ms.
[        ] ensureAnalyticsSent: 0ms
[        ] Running 1 shutdown hook
[        ] Shutdown hooks complete
[        ] exiting with code 0

Flutter Doctor

[!] Flutter (Channel [user-branch], 3.19.1, on macOS 14.5 23F79 darwin-x64, locale en-US)
    ! Flutter version 3.19.1 on channel [user-branch] at /Users/[removed]/Desktop/work/flutter
      Currently on an unknown channel. Run `flutter channel` to switch to an official channel.
      If that doesn't fix the issue, reinstall Flutter by following instructions at https://flutter.dev/docs/get-started/install.
    ! Upstream repository unknown source is not a standard remote.
      Set environment variable "FLUTTER_GIT_URL" to unknown source to dismiss this error.
    • Framework revision abb292a07e (7 months ago), 2024-02-20 14:35:05 -0800
    • Engine revision 04817c99c9
    • Dart version 3.3.0
    • DevTools version 2.31.1
    • If those were intentional, you can disregard the above warnings; however it is recommended to use "git" directly to perform update checks and upgrades.

[✓] Android toolchain - develop for Android devices (Android SDK version 34.0.0)
    • Android SDK at /Users/[removed]/Library/Android/sdk
    • Platform android-34, build-tools 34.0.0
    • Java binary at: /Applications/Android Studio.app/Contents/jbr/Contents/Home/bin/java
    • Java version OpenJDK Runtime Environment (build 17.0.11+0-17.0.11b1207.24-11852314)
    • All Android licenses accepted.

[✓] Xcode - develop for iOS and macOS (Xcode 15.4)
    • Xcode at /Applications/Xcode.app/Contents/Developer
    • Build 15F31d
    • CocoaPods version 1.15.2

[✓] Android Studio (version 2024.1)
    • Android Studio at /Applications/Android Studio.app/Contents
    • Flutter plugin can be installed from:
      🔨 https://plugins.jetbrains.com/plugin/9212-flutter
    • Dart plugin can be installed from:
      🔨 https://plugins.jetbrains.com/plugin/6351-dart
    • Java version OpenJDK Runtime Environment (build 17.0.11+0-17.0.11b1207.24-11852314)

[✓] IntelliJ IDEA Ultimate Edition (version 2022.1)
    • IntelliJ at /Applications/IntelliJ IDEA.app
    • Flutter plugin can be installed from:
      🔨 https://plugins.jetbrains.com/plugin/9212-flutter
    • Dart plugin can be installed from:
      🔨 https://plugins.jetbrains.com/plugin/6351-dart

Checklist before submitting a bug

  • I searched issues in this repository and couldn't find such bug/problem
  • I Google'd a solution and I couldn't find it
  • I searched on StackOverflow for a solution and I couldn't find it
  • I read the README.md file of the plugin
  • I'm using the latest version of the plugin
  • All dependencies are up to date with flutter pub upgrade
  • I did a flutter clean
  • I tried running the example project
@mposch-Z mposch-Z added bug Something isn't working triage labels Sep 9, 2024
@miquelbeltran
Copy link
Member

I am not sure if I understand the issue, is this what you are seeing?

  • App is in release mode, running in the foreground.
  • You then leave the app (don't kill it)
  • You disable all connectivity
  • You come back to the app -> Connectivity is wifi?
  • You enable all connectivity again -> Connectivity is wifi?

I don't think the issue is the distinct, but rather the fact that the none event is never received.

I'd recommend you to use the normal get connectivity method in addition to the onConnectivityChanged, and implement the widget/app lifecycle properly, obtaining a fresh connectivity status when the app comes back to foreground, instead of relying on the events by the onConnectivityChanged.

@mposch-Z
Copy link
Author

mposch-Z commented Sep 10, 2024

  • App is in release mode, running in the foreground WITH EXISTING WIFI network connection, call it wifi network A
  • App is minimized in order to open Settings Application Menu -> Wifi and connect to a second wifi network, "wifi network B"
  • When app is brought back to foreground -> connectivity is still 'wifi' & onConnectionChanged callback is not invoked. It appears due to the previous event on the stream matching the current event on the stream (both being Connectivity.wifi). Since the disconnect doesn't appear to be recognized in the background (meaning no onConnectivityChanged invoked during disconnect/change to Connectivity.none) the distinct method on stream is filtering out the perceived 'repeated' Connectivity.wifi event on the stream, b/c the status matches what it previously was when the app was ORIGINALLY removed from the foreground with intact wifi connection A.

Removing the distinct application on the stream resolves the issue in my testing of this scenario (tested by editing local pub cached version).
Using the lifecycle hooks would result in the same deprecated experience. App leaves foreground (enters onPause) with a valid network connection. Connection is changed in the background. App brought back in to focus (onResume) with a NEW valid connection but no onConnectivityChanged invocations will occur. With your advised approach, in theory, wouldn't that mean I should be verifying ALL potential system settings changes explicitly during lifecycle state changes as opposed to an optimization where only certain settings can be addressed based on callback invocations which imply changes?

@miquelbeltran
Copy link
Member

I should be verifying ALL potential system settings changes explicitly during lifecycle state changes as opposed

Yes, you already mention the problem with relying on a stream, even without the distinct() you are not properly receiving change events when the app is in the background as a release build.

My advice remains the same, don't rely on a stream that doesn't work as expected (even without distinct) and handle the lifecycle of the app, read the system status when the app goes back into foreground. You can still subscribe to changes, of course.

Anyway, we decided to add distinct because the stream would expose an overwhelming amount of events (as it is directly hooked to the OS callbacks). I don't think we will back that decision, but I'd be open to add a new method e.g. onConnectivityChangedRaw that exposes the stream without distinct on it, as it shouldn't break any existing implementation.

@mposch-Z
Copy link
Author

Yes, you already mention the problem with relying on a stream, even without the distinct() you are not properly receiving change events when the app is in the background as a release build.

I agree, I'm not receiving the connectivity status change to none but I am receiving an updated status via onConnectivityChanged => connectivity.wifi when the app is brought back in to the foreground which still indicates a new wifi connection, which is helpful. In this case we know to resubscribe to a gRPC channel using the new network information.

My advice remains the same, don't rely on a stream that doesn't work as expected (even without distinct) and handle the lifecycle of the app, read the system status when the app goes back into foreground. You can still subscribe to changes, of course.

That's fair.

Anyway, we decided to add distinct because the stream would expose an overwhelming amount of events (as it is directly hooked to the OS callbacks). I don't think we will back that decision, but I'd be open to add a new method e.g. onConnectivityChangedRaw that exposes the stream without distinct on it, as it shouldn't break any existing implementation.

Understood, and would appreciate if you further considered adding onConnectivityChangedRaw

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
bug Something isn't working triage
Projects
None yet
Development

No branches or pull requests

2 participants