Skip to content

[camera] CameraController.setDescription and dispose don't work as expected #126823

Closed

Description

@jellynoone

Is there an existing issue for this?

Steps to reproduce

  1. Initialize a CameraController
  2. Set a different CameraDescription via setDescription
  3. Dispose of the controller
  4. Initialize a new CameraController
  5. Observer a ChangeNotifier exception

Expected results

No ChangeNotifier exceptions.

Actual results

E/flutter (12815): Once you have called dispose() on a CameraController, it can no longer be used.
E/flutter (12815): #0      ChangeNotifier.debugAssertNotDisposed.<anonymous closure>
change_notifier.dart:179
E/flutter (12815): #1      ChangeNotifier.debugAssertNotDisposed
change_notifier.dart:186
E/flutter (12815): #2      ChangeNotifier.notifyListeners
change_notifier.dart:382
E/flutter (12815): #3      ValueNotifier.value=
change_notifier.dart:530
E/flutter (12815): #4      CameraController._initializeWithDescription.<anonymous closure>
camera_controller.dart:304
E/flutter (12815): #5      _RootZone.runUnaryGuarded (dart:async/zone.dart:1594:10)
E/flutter (12815): #6      _BufferingStreamSubscription._sendData (dart:async/stream_impl.dart:339:11)
E/flutter (12815): #7      _BufferingStreamSubscription._add (dart:async/stream_impl.dart:271:7)
E/flutter (12815): #8      _SyncBroadcastStreamController._sendData (dart:async/broadcast_stream_controller.dart:377:25)
E/flutter (12815): #9      _BroadcastStreamController.add (dart:async/broadcast_stream_controller.dart:244:5)
E/flutter (12815): #10     Where.whereType.<anonymous closure>
where.dart:21
E/flutter (12815): #11     TransformByHandlers.transformByHandlers.<anonymous closure>.<anonymous closure>
from_handlers.dart:29
E/flutter (12815): #12     _RootZone.runUnaryGuarded (dart:async/zone.dart:1594:10)
E/flutter (12815): #13     _BufferingStreamSubscription._sendData (dart:async/stream_impl.dart:339:11)
E/flutter (12815): #14     _DelayedData.perform (dart:async/stream_impl.dart:515:14)
E/flutter (12815): #15     _PendingEvents.handleNext (dart:async/stream_impl.dart:620:11)
E/flutter (12815): #16     _PendingEvents.schedule.<anonymous closure> (dart:async/stream_impl.dart:591:7)
E/flutter (12815): #17     _microtaskLoop (dart:async/schedule_microtask.dart:40:21)
E/flutter (12815): #18     _startMicrotaskLoop (dart:async/schedule_microtask.dart:49:5)

Code sample

Not providing a code sample since, I think I know where the issue is:

If we look at:
CameraController.setDescription we see the new description is set up by calling _initializeWithDescription.

If we look at _initializeWithDescription, we see _deviceOrientationSubscription is set up through direct assignment and subscription to the CameraPlatform.instance.onDeviceOrientationChanged() stream.

Code:

      _deviceOrientationSubscription = CameraPlatform.instance
          .onDeviceOrientationChanged()
          .listen((DeviceOrientationChangedEvent event) {
        value = value.copyWith(
          deviceOrientation: event.orientation,
        );
      });

The _deviceOrientationSubscription is never cancelled in case we set up a new description, it is simply reassigned.

My guess would be to simply assign the _deviceOrientationSubscription using ??=.

Screenshots or Video

No response

Logs

No response

Flutter Doctor output

Doctor output
[✓] Flutter (Channel stable, 3.10.0, on macOS 11.7.6 20G1231 darwin-x64, locale en-GB)
    • Flutter version 3.10.0 on channel stable at /usr/local/flutter
    • Upstream repository https://github.com/flutter/flutter.git
    • Framework revision 84a1e904f4 (6 days ago), 2023-05-09 07:41:44 -0700
    • Engine revision d44b5a94c9
    • Dart version 3.0.0
    • DevTools version 2.23.1

[✓] Android toolchain - develop for Android devices (Android SDK version 33.0.0)
    • Android SDK at /Users/jellynoone/Library/Android/sdk
    • Platform android-33, build-tools 33.0.0
    • Java binary at: /Applications/Android Studio.app/Contents/jbr/Contents/Home/bin/java
    • Java version OpenJDK Runtime Environment (build 17.0.6+0-17.0.6b802.4-9586694)
    • All Android licenses accepted.

[!] Xcode - develop for iOS and macOS (Xcode 13.2.1)
    • Xcode at /Applications/Xcode.app/Contents/Developer
    • Build 13C100
    ✗ CocoaPods not installed.
        CocoaPods is used to retrieve the iOS and macOS platform side's plugin code that responds to your plugin usage on the Dart side.
        Without CocoaPods, plugins will not work on iOS or macOS.
        For more info, see https://flutter.dev/platform-plugins
      To install see https://guides.cocoapods.org/using/getting-started.html#installation for instructions.

[✓] Chrome - develop for the web
    • Chrome at /Applications/Google Chrome.app/Contents/MacOS/Google Chrome

[✓] Android Studio (version 2022.2)
    • 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.6+0-17.0.6b802.4-9586694)

[✓] VS Code (version 1.79.0-insider)
    • VS Code at /Applications/Visual Studio Code - Insiders.app/Contents
    • Flutter extension version 3.64.0

[✓] Connected device (3 available)
    • Pixel (mobile)  • FA76R0301797 • android-arm64  • Android 10 (API 29)
    • macOS (desktop) • macos        • darwin-x64     • macOS 11.7.6 20G1231 darwin-x64
    • Chrome (web)    • chrome       • web-javascript • Google Chrome 113.0.5672.92

[✓] Network resources
    • All expected network resources are available.

! Doctor found issues in 1 category.

Activity

  1. jellynoone commented on May 15, 2023

    @jellynoone
    ContributorAuthor

    Further analysis:
    So the error I'm getting is really an error that happens due to the subscription not being cancelled after a new CameraDescription is set while the controller is active.

    We dispose the new subscription that is made up in the second initialization call but the first one gets lost in the process.

    When we then dispose the controller, the subscription is still active.

    I think its fine to simply write:

          _deviceOrientationSubscription ??= CameraPlatform.instance
              .onDeviceOrientationChanged()
              .listen((DeviceOrientationChangedEvent event) {
            value = value.copyWith(
              deviceOrientation: event.orientation,
            );
          });
  2. jellynoone commented on May 15, 2023

    @jellynoone
    ContributorAuthor

    Additionally, I'm not entirely sure simply initialising the new camera is enough here. Shouldn't we first dispose the old camera id? Using, CameraPlatform.instance.dispose.

    cc: @BradenBagby, @stuartmorgan

  3. BradenBagby commented on May 15, 2023

    @BradenBagby

    Thanks for catching this! Are you able to provide a code sample? The camera example app appears to work with no errors

  4. BradenBagby commented on May 15, 2023

    @BradenBagby

    I have modified the example camera code to dispose and re-initialize the camera controller every time and am still not seeing any errors

  5. jellynoone commented on May 15, 2023

    @jellynoone
    ContributorAuthor

    Example below:

    import 'package:camera/camera.dart';
    import 'package:flutter/material.dart';
    
    void main() async {
      WidgetsFlutterBinding.ensureInitialized();
    
      final cameras = await availableCameras();
      assert(cameras.length > 1);
      runApp(MyApp(cameras: Cameras(cameras[0], cameras[1])));
    }
    
    class Cameras {
      final CameraDescription camera1;
      final CameraDescription camera2;
    
      Cameras(this.camera1, this.camera2);
    }
    
    class MyApp extends StatefulWidget {
      final Cameras cameras;
    
      const MyApp({
        super.key,
        required this.cameras,
      });
    
      @override
      State<MyApp> createState() => _MyAppState();
    }
    
    class _MyAppState extends State<MyApp> {
      bool _showBody = true;
    
      @override
      Widget build(BuildContext context) {
        return MaterialApp(
          home: Scaffold(
            body: _showBody
                ? _Body(
                    cameras: widget.cameras,
                  )
                : SizedBox.shrink(),
            floatingActionButton: FloatingActionButton(
              child: Text(
                _showBody ? 'Tap me after camera change' : 'Tap me again',
              ),
              onPressed: onTap,
            ),
          ),
        );
      }
    
      void onTap() {
        setState(() {
          _showBody = !_showBody;
        });
      }
    }
    
    class _Body extends StatefulWidget {
      final Cameras cameras;
    
      const _Body({
        super.key,
        required this.cameras,
      });
    
      @override
      State<_Body> createState() => _BodyState();
    }
    
    class _BodyState extends State<_Body> {
      late final CameraController controller;
      Future<void>? initialize;
      bool useFirst = true;
    
      @override
      void initState() {
        super.initState();
    
        controller = CameraController(widget.cameras.camera1, ResolutionPreset.max);
        initialize = controller.initialize().whenComplete(() {
          setState(() {
            initialize = null;
          });
        });
      }
    
      @override
      void dispose() {
        controller.dispose();
        super.dispose();
      }
    
      @override
      Widget build(BuildContext context) {
        if (initialize == null) {
          return Stack(
            children: [
              CameraPreview(controller),
              Align(
                  alignment: Alignment.centerLeft,
                  child: FloatingActionButton(
                    child: Text('Change camera'),
                    onPressed: _change,
                  )),
            ],
          );
        } else {
          return Center(
            child: CircularProgressIndicator(),
          );
        }
      }
    
      void _change() {
        useFirst = !useFirst;
        controller.setDescription(
          useFirst ? widget.cameras.camera1 : widget.cameras.camera2,
        );
      }
    }
    
    1. Wait for camera to initialize and start displaying
    2. Then tap change camera, wait for the display to come on
    3. Then tap 'Tap me after camera change'
    4. Then wait a bit
    5. Then tap 'Tap me again'

    If you have uncaught exceptions enabled, you should see the exception in the editor, otherwise in the logs.

  6. BradenBagby commented on May 15, 2023

    @BradenBagby

    Thank you I am seeing the error!

  7. darshankawar commented on May 16, 2023

    @darshankawar
    Member

    Thanks for the detailed report. I was able to replicate the reported behavior.

    stable, master flutter doctor -v
    [!] Flutter (Channel stable, 3.10.0, on macOS 12.2.1 21D62 darwin-x64, locale
        en-GB)
        • Flutter version 3.10.0 on channel stable at
          /Users/dhs/documents/fluttersdk/flutter
        ! Warning: `flutter` on your path resolves to
          /Users/dhs/Documents/Fluttersdk/flutter/bin/flutter, which is not inside
          your current Flutter SDK checkout at
          /Users/dhs/documents/fluttersdk/flutter. Consider adding
          /Users/dhs/documents/fluttersdk/flutter/bin to the front of your path.
        ! Warning: `dart` on your path resolves to
          /Users/dhs/Documents/Fluttersdk/flutter/bin/dart, which is not inside your
          current Flutter SDK checkout at /Users/dhs/documents/fluttersdk/flutter.
          Consider adding /Users/dhs/documents/fluttersdk/flutter/bin to the front
          of your path.
        • Upstream repository https://github.com/flutter/flutter.git
        • Framework revision 84a1e904f4 (2 days ago), 2023-05-09 07:41:44 -0700
        • Engine revision d44b5a94c9
        • Dart version 3.0.0
        • DevTools version 2.23.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.
    
    [!] Xcode - develop for iOS and macOS (Xcode 12.3)
        • Xcode at /Applications/Xcode.app/Contents/Developer
        ! Flutter recommends a minimum Xcode version of 13.
          Download the latest version or update via the Mac App Store.
        • CocoaPods version 1.11.2
    
    [✓] Chrome - develop for the web
        • Chrome at /Applications/Google Chrome.app/Contents/MacOS/Google Chrome
    
    [✓] VS Code (version 1.62.0)
        • VS Code at /Applications/Visual Studio Code.app/Contents
        • Flutter extension version 3.21.0
    
    [✓] Connected device (5 available)
        • SM G975F (mobile)       • RZ8M802WY0X • android-arm64   • Android 11 (API 30)
        • Darshan's iphone (mobile)  • 21150b119064aecc249dfcfe05e259197461ce23 •
          ios            • iOS 14.4.1 18D61
        • iPhone 12 Pro Max (mobile) • A5473606-0213-4FD8-BA16-553433949729     •
          ios            • com.apple.CoreSimulator.SimRuntime.iOS-14-3 (simulator)
        • macOS (desktop)            • macos                                    •
          darwin-x64     • Mac OS X 10.15.4 19E2269 darwin-x64
        • Chrome (web)               • chrome                                   •
          web-javascript • Google Chrome 98.0.4758.80
    
    [✓] HTTP Host Availability
        • All required HTTP hosts are available
    
    ! Doctor found issues in 1 category.
    
    [!] Flutter (Channel master, 3.11.0-6.0.pre.86, on macOS 12.2.1 21D62
        darwin-x64, locale en-GB)
        • Flutter version 3.11.0-6.0.pre.86 on channel master at
          /Users/dhs/documents/fluttersdk/flutter
        ! Warning: `flutter` on your path resolves to
          /Users/dhs/Documents/Fluttersdk/flutter/bin/flutter, which is not inside
          your current Flutter SDK checkout at
          /Users/dhs/documents/fluttersdk/flutter. Consider adding
          /Users/dhs/documents/fluttersdk/flutter/bin to the front of your path.
        ! Warning: `dart` on your path resolves to
          /Users/dhs/Documents/Fluttersdk/flutter/bin/dart, which is not inside your
          current Flutter SDK checkout at /Users/dhs/documents/fluttersdk/flutter.
          Consider adding /Users/dhs/documents/fluttersdk/flutter/bin to the front
          of your path.
        • Upstream repository https://github.com/flutter/flutter.git
        • Framework revision ea5eddb5a9 (55 minutes ago), 2023-05-15 21:39:26 -0700
        • Engine revision c4d4b40c65
        • Dart version 3.1.0 (build 3.1.0-113.0.dev)
        • DevTools version 2.23.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 30.0.3)
        • Android SDK at /Users/dhs/Library/Android/sdk
        ✗ cmdline-tools component is missing
          Run `path/to/sdkmanager --install "cmdline-tools;latest"`
          See https://developer.android.com/studio/command-line for more details.
        ✗ Android license status unknown.
          Run `flutter doctor --android-licenses` to accept the SDK licenses.
          See https://flutter.dev/docs/get-started/install/macos#android-setup for
          more details.
    
    [✓] Xcode - develop for iOS and macOS (Xcode 13.2.1)
        • Xcode at /Applications/Xcode.app/Contents/Developer
        • Build 13C100
        • CocoaPods version 1.11.2
    
    [✓] Chrome - develop for the web
        • Chrome at /Applications/Google Chrome.app/Contents/MacOS/Google Chrome
    
    [✓] IntelliJ IDEA Ultimate Edition (version 2021.3.2)
        • IntelliJ at /Applications/IntelliJ IDEA.app
        • Flutter plugin version 65.1.4
        • Dart plugin version 213.7228
    
    [✓] VS Code (version 1.62.0)
        • VS Code at /Applications/Visual Studio Code.app/Contents
        • Flutter extension version 3.29.0
    
    [✓] Connected device (3 available)
        • Darshan's iphone (mobile) • 21150b119064aecc249dfcfe05e259197461ce23 • ios
          • iOS 15.3.1 19D52
        • macOS (desktop)           • macos                                    •
          darwin-x64     • macOS 12.2.1 21D62 darwin-x64
        • Chrome (web)              • chrome                                   •
          web-javascript • Google Chrome 109.0.5414.119
    
    [✓] Network resources
        • All expected network resources are available.
    
    ! Doctor found issues in 1 category.
          
    [!] Xcode - develop for iOS and macOS (Xcode 12.3)
        • Xcode at /Applications/Xcode.app/Contents/Developer
        ! Flutter recommends a minimum Xcode version of 13.
          Download the latest version or update via the Mac App Store.
        • CocoaPods version 1.11.2
    
    [✓] Chrome - develop for the web
        • Chrome at /Applications/Google Chrome.app/Contents/MacOS/Google Chrome
    
    [✓] VS Code (version 1.62.0)
        • VS Code at /Applications/Visual Studio Code.app/Contents
        • Flutter extension version 3.21.0
    
    [✓] Connected device (5 available)
        • SM G975F (mobile)       • RZ8M802WY0X • android-arm64   • Android 11 (API 30)
        • Darshan's iphone (mobile)  • 21150b119064aecc249dfcfe05e259197461ce23 •
          ios            • iOS 14.4.1 18D61
        • iPhone 12 Pro Max (mobile) • A5473606-0213-4FD8-BA16-553433949729     •
          ios            • com.apple.CoreSimulator.SimRuntime.iOS-14-3 (simulator)
        • macOS (desktop)            • macos                                    •
          darwin-x64     • Mac OS X 10.15.4 19E2269 darwin-x64
        • Chrome (web)               • chrome                                   •
          web-javascript • Google Chrome 98.0.4758.80
    
    [✓] HTTP Host Availability
        • All required HTTP hosts are available
    
    ! Doctor found issues in 1 category.
    
    
    
    
  8. added
    packageflutter/packages repository. See also p: labels.
    has reproducible stepsThe issue has been confirmed reproducible and is ready to work on
    and removed
    in triagePresently being triaged by the triage team
    on May 16, 2023
  9. added
    P2Important issues not at the top of the work list
    on May 16, 2023
  10. ibrahimdevs commented on May 30, 2023

    @ibrahimdevs

    After hours of struggle, finally I can able to think that it may not my fault :)
    I can confirm this issue. This is totally related with "setDescription" function.
    As a not optimum workaround, you can dispose the cameraController and init again.

  11. Sh1d0w commented on Jun 3, 2023

    @Sh1d0w

    @ibrahimdevs thanks for the solution, works for now.

    I was going insane debugging the issue for hours, I thought it was issue in my code. Hope it gets fixed soon.

  12. namanshergill commented on Jan 16, 2024

    @namanshergill

    Shouldn’t this issue be closed now that the fix is released?

  13. stuartmorgan-g commented on Jan 16, 2024

    @stuartmorgan-g
    Contributor

    Thanks for noticing; the PR just didn't have quite the right phrasing to have GitHub auto-close the issue.

  14. added
    r: fixedIssue is closed as already fixed in a newer version
    on Jan 17, 2024
  15. github-actions commented on Jan 31, 2024

    @github-actions

    This thread has been automatically locked since there has not been any recent activity after it was closed. If you are still experiencing a similar issue, please open a new bug, including the output of flutter doctor -v and a minimal reproduction of the issue.

  16. locked as resolved and limited conversation to collaborators on Jan 31, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    P2Important issues not at the top of the work listfound in release: 3.10Found to occur in 3.10found in release: 3.11Found to occur in 3.11has reproducible stepsThe issue has been confirmed reproducible and is ready to work onp: cameraThe camera pluginpackageflutter/packages repository. See also p: labels.r: fixedIssue is closed as already fixed in a newer versionteam-ecosystemOwned by Ecosystem teamtriaged-ecosystemTriaged by Ecosystem team

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions