Skip to content

camera_android_camerax: Failed to find supported resolutions (IllegalArgumentException) #135293

Description

@andynewman10

Is there an existing issue for this?

Steps to reproduce

  1. Create a Flutter application using Flutter 3.13.3. I use VS Code on Windows.
  2. Design a basic camera application using:
camera: ^0.10.5+4
camera_android_camerax: ^0.5.0+18
  1. Create a camera controller in the following way:
    List<CameraDescription> cameras = await availableCameras();

    CameraDescription? cameraDescription;
    for (int i = 0; i < cameras.length; i++) {
      if (cameras[i].lensDirection == CameraLensDirection.back) {
        cameraDescription = cameras[i];
      }
    }

    if (cameraDescription == null) {
      throw Exception("Could not find any back-facing camera");
    }

    final cameraController = CameraController(
        cameraDescription, ResolutionPreset.medium,
        enableAudio: false, imageFormatGroup: ImageFormatGroup.yuv420);

    await cameraController.initialize();
  1. Run the application on an Android 13 device, I personally use a Google Pixel 6a.
  2. The following exception is thrown:
IllegalArgumentException: Failed to find supported resolutions
  1. Now, remove the following line from your pubspec.yaml:
# camera_android_camerax: ^0.5.0+18
  1. Run the application again: no error.

Expected results

The code should be running fine.

Actual results

Exception being thrown.

Code sample

Code sample
See above

Screenshots or Video

Screenshots / Video demonstration

[Upload media here]

Logs

Logs
[Paste your logs here]

Flutter Doctor output

Doctor output
[√] Flutter (Channel stable, 3.13.3, on Microsoft Windows [version 10.0.22000.2416], locale fr-FR)
    • Flutter version 3.13.3 on channel stable at C:\Users\andy\Documents\flutter
    • Upstream repository https://github.com/flutter/flutter.git
    • Framework revision 2524052335 (2 weeks ago), 2023-09-06 14:32:31 -0700
    • Engine revision b8d35810e9
    • Dart version 3.1.1
    • DevTools version 2.25.0

[√] Windows Version (Installed version of Windows is version 10 or higher)

[√] Android toolchain - develop for Android devices (Android SDK version 34.0.0)
    • Android SDK at C:\Users\andy\AppData\Local\Android\sdk
    • Platform android-33, build-tools 34.0.0
    • Java binary at: C:\Users\andy\Documents\Applications\android-studio\jbr\bin\java
    • Java version OpenJDK Runtime Environment (build 11.0.15+0-b2043.56-9505619)
    • All Android licenses accepted.

[√] Chrome - develop for the web
    • Chrome at C:\Program Files\Google\Chrome\Application\chrome.exe

[√] Visual Studio - develop Windows apps (Visual Studio Community 2022 17.0.2)
    • Visual Studio at C:\Program Files\Microsoft Visual Studio\2022\Community
    • Visual Studio Community 2022 version 17.0.31919.166
    • Windows 10 SDK version 10.0.19041.0

[√] Android Studio (version 2022.2)
    • Android Studio at C:\Users\andy\Documents\Applications\android-studio
    • 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 11.0.15+0-b2043.56-9505619)

[√] IntelliJ IDEA Community Edition (version 2021.3)
    • IntelliJ at C:\Users\andy\Documents\Applications\IntelliJ
    • 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

[√] VS Code (version 1.82.2)
    • VS Code at C:\Users\andy\AppData\Local\Programs\Microsoft VS Code
    • Flutter extension version 3.72.0

[√] Connected device (4 available)
    • Pixel 6a (mobile) • 29231JEGR03669 • android-arm64  • Android 13 (API 33)
    • Windows (desktop) • windows        • windows-x64    • Microsoft Windows [version 10.0.22000.2416]
    • Chrome (web)      • chrome         • web-javascript • Google Chrome 116.0.5845.188
    • Edge (web)        • edge           • web-javascript • Microsoft Edge 117.0.2045.36

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

• No issues found!

Activity

  1. darshankawar commented on Sep 22, 2023

    @darshankawar
    Member

    Thanks for the report @andynewman10
    Although I am not using VSCode + windows setup, I tried the code sample as below on Pixel 6 emulator (due to lack of said device) with which I wasn't able to replicate the reported error. I get below log in console while operating the app:

    D/CameraStateMachine(16358): Publishing new public camera state CameraState{type=OPENING, error=null}
    D/DeferrableSurface(16358): Surface created[total_surfaces=4, used_surfaces=1](androidx.camera.core.impl.ImmediateSurface@a7f79b}
    D/UseCaseAttachState(16358): All use case: [androidx.camera.core.Preview-8d9f66ca-2b84-475d-b039-eddd78007a72179727171] for camera: 0
    D/CameraOrientationUtil(16358): getRelativeImageRotation: destRotationDegrees=90, sourceRotationDegrees=90, isOppositeFacing=true, result=0
    D/Camera2CameraImpl(16358): {Camera@cacb0ac[id=0]} Use case androidx.camera.core.ImageCapture-5a8430de-c724-4c6b-8b6a-d2cbb6abf8fa3176497 ACTIVE
    D/UseCaseAttachState(16358): Active and attached use case: [androidx.camera.core.Preview-8d9f66ca-2b84-475d-b039-eddd78007a72179727171] for camera: 0
    D/UseCaseAttachState(16358): Active and attached use case: [androidx.camera.core.Preview-8d9f66ca-2b84-475d-b039-eddd78007a72179727171] for camera: 0
    D/Camera2CameraImpl(16358): {Camera@cacb0ac[id=0]} Use cases [androidx.camera.core.ImageCapture-5a8430de-c724-4c6b-8b6a-d2cbb6abf8fa3176497, androidx.camera.core.ImageAnalysis-9e4d1fda-dd22-4c63-b302-d8139e41075717620119] now ATTACHED
    D/UseCaseAttachState(16358): All use case: [androidx.camera.core.Preview-8d9f66ca-2b84-475d-b039-eddd78007a72179727171, androidx.camera.core.ImageCapture-5a8430de-c724-4c6b-8b6a-d2cbb6abf8fa3176497, androidx.camera.core.ImageAnalysis-9e4d1fda-dd22-4c63-b302-d8139e41075717620119] for camera: 0
    D/UseCaseAttachState(16358): Active and attached use case: [androidx.camera.core.Preview-8d9f66ca-2b84-475d-b039-eddd78007a72179727171, androidx.camera.core.ImageCapture-5a8430de-c724-4c6b-8b6a-d2cbb6abf8fa3176497] for camera: 0
    D/Camera2CameraImpl(16358): {Camera@cacb0ac[id=0]} Resetting Capture Session
    D/Camera2CameraImpl(16358): {Camera@cacb0ac[id=0]} Releasing session in state OPENING
    D/Camera2CameraImpl(16358): {Camera@cacb0ac[id=0]} open() ignored due to being in state: OPENING
    D/Camera2CameraImpl(16358): {Camera@cacb0ac[id=0]} Use case androidx.camera.core.ImageCapture-5a8430de-c724-4c6b-8b6a-d2cbb6abf8fa3176497 ACTIVE
    D/UseCaseAttachState(16358): Active and attached use case: [androidx.camera.core.Preview-8d9f66ca-2b84-475d-b039-eddd78007a72179727171, androidx.camera.core.ImageCapture-5a8430de-c724-4c6b-8b6a-d2cbb6abf8fa3176497] for camera: 0
    D/Camera2CameraImpl(16358): {Camera@cacb0ac[id=0]} Use case androidx.camera.core.ImageAnalysis-9e4d1fda-dd22-4c63-b302-d8139e41075717620119 INACTIVE
    D/UseCaseAttachState(16358): Active and attached use case: [androidx.camera.core.Preview-8d9f66ca-2b84-475d-b039-eddd78007a72179727171, androidx.camera.core.ImageCapture-5a8430de-c724-4c6b-8b6a-d2cbb6abf8fa3176497] for camera: 0
    D/Camera2CameraImpl(16358): {Camera@cacb0ac[id=0]} CameraDevice.onOpened()
    D/Camera2CameraImpl(16358): {Camera@cacb0ac[id=0]} Transitioning camera internal state: OPENING --> OPENED
    D/CameraStateRegistry(16358): Recalculating open cameras:
    D/CameraStateRegistry(16358): Camera                                       State                 
    D/CameraStateRegistry(16358): -------------------------------------------------------------------
    D/CameraStateRegistry(16358): Camera@cacb0ac[id=0]                         OPEN                  
    D/CameraStateRegistry(16358): Camera@2f09a57[id=1]                         UNKNOWN               
    D/CameraStateRegistry(16358): -------------------------------------------------------------------
    D/CameraStateRegistry(16358): Open count: 1 (Max allowed: 1)
    D/CameraStateMachine(16358): New public camera state CameraState{type=OPEN, error=null} from OPEN and null
    D/CameraStateMachine(16358): Publishing new public camera state CameraState{type=OPEN, error=null}
    D/UseCaseAttachState(16358): All use case: [androidx.camera.core.Preview-8d9f66ca-2b84-475d-b039-eddd78007a72179727171, androidx.camera.core.ImageCapture-5a8430de-c724-4c6b-8b6a-d2cbb6abf8fa3176497, androidx.camera.core.ImageAnalysis-9e4d1fda-dd22-4c63-b302-d8139e41075717620119] for camera: 0
    D/UseCaseAttachState(16358): Active and attached use case: [androidx.camera.core.Preview-8d9f66ca-2b84-475d-b039-eddd78007a72179727171, androidx.camera.core.ImageCapture-5a8430de-c724-4c6b-8b6a-d2cbb6abf8fa3176497] for camera: 0
    D/SyncCaptureSessionBase(16358): [androidx.camera.camera2.internal.SynchronizedCaptureSessionBaseImpl@48b3b0a] getSurface...done
    D/CaptureSession(16358): Opening capture session.
    D/DeferrableSurface(16358): New surface in use[total_surfaces=4, used_surfaces=2](androidx.camera.core.processing.SurfaceEdge$SettableSurface@7b5a6ee}
    D/DeferrableSurface(16358): use count+1, useCount=1 androidx.camera.core.processing.SurfaceEdge$SettableSurface@7b5a6ee
    D/DeferrableSurface(16358): New surface in use[total_surfaces=4, used_surfaces=3](androidx.camera.core.impl.ImmediateSurface@182c723}
    D/DeferrableSurface(16358): use count+1, useCount=1 androidx.camera.core.impl.ImmediateSurface@182c723
    D/DeferrableSurface(16358): New surface in use[total_surfaces=4, used_surfaces=4](androidx.camera.core.impl.ImmediateSurface@a7f79b}
    D/DeferrableSurface(16358): use count+1, useCount=1 androidx.camera.core.impl.ImmediateSurface@a7f79b
    D/CaptureSession(16358): Attempting to send capture request onConfigured
    D/CaptureSession(16358): Issuing request for session.
    D/Camera2CaptureRequestBuilder(16358): createCaptureRequest
    D/CaptureSession(16358): CameraCaptureSession.onConfigured() mState=OPENED
    D/CaptureSession(16358): CameraCaptureSession.onReady() OPENED
    D/EGL_emulation(16358): app_time_stats: avg=70.95ms min=23.70ms max=395.47ms count=18
    
    runnable code sample
    
    // Copyright 2013 The Flutter Authors. All rights reserved.
    // Use of this source code is governed by a BSD-style license that can be
    // found in the LICENSE file.
    
    import 'dart:async';
    import 'dart:io';
    
    import 'package:camera/camera.dart';
    import 'package:flutter/foundation.dart';
    import 'package:flutter/material.dart';
    import 'package:flutter/scheduler.dart';
    import 'package:video_player/video_player.dart';
    
    /// Camera example home widget.
    class CameraExampleHome extends StatefulWidget {
      /// Default Constructor
      const CameraExampleHome({super.key});
    
      @override
      State<CameraExampleHome> createState() {
        return _CameraExampleHomeState();
      }
    }
    
    /// Returns a suitable camera icon for [direction].
    IconData getCameraLensIcon(CameraLensDirection direction) {
      switch (direction) {
        case CameraLensDirection.back:
          return Icons.camera_rear;
        case CameraLensDirection.front:
          return Icons.camera_front;
        case CameraLensDirection.external:
          return Icons.camera;
      }
      // This enum is from a different package, so a new value could be added at
      // any time. The example should keep working if that happens.
      // ignore: dead_code
      return Icons.camera;
    }
    
    void _logError(String code, String? message) {
      // ignore: avoid_print
      print('Error: $code${message == null ? '' : '\nError Message: $message'}');
    }
    
    class _CameraExampleHomeState extends State<CameraExampleHome>
        with WidgetsBindingObserver, TickerProviderStateMixin {
      CameraController? controller;
      XFile? imageFile;
      XFile? videoFile;
      VideoPlayerController? videoController;
      VoidCallback? videoPlayerListener;
      bool enableAudio = true;
      double _minAvailableExposureOffset = 0.0;
      double _maxAvailableExposureOffset = 0.0;
      double _currentExposureOffset = 0.0;
      late AnimationController _flashModeControlRowAnimationController;
      late Animation<double> _flashModeControlRowAnimation;
      late AnimationController _exposureModeControlRowAnimationController;
      late Animation<double> _exposureModeControlRowAnimation;
      late AnimationController _focusModeControlRowAnimationController;
      late Animation<double> _focusModeControlRowAnimation;
      double _minAvailableZoom = 1.0;
      double _maxAvailableZoom = 1.0;
      double _currentScale = 1.0;
      double _baseScale = 1.0;
    
      // Counting pointers (number of user fingers on screen)
      int _pointers = 0;
    
      @override
      void initState() {
        super.initState();
        WidgetsBinding.instance.addObserver(this);
    
        _flashModeControlRowAnimationController = AnimationController(
          duration: const Duration(milliseconds: 300),
          vsync: this,
        );
        _flashModeControlRowAnimation = CurvedAnimation(
          parent: _flashModeControlRowAnimationController,
          curve: Curves.easeInCubic,
        );
        _exposureModeControlRowAnimationController = AnimationController(
          duration: const Duration(milliseconds: 300),
          vsync: this,
        );
        _exposureModeControlRowAnimation = CurvedAnimation(
          parent: _exposureModeControlRowAnimationController,
          curve: Curves.easeInCubic,
        );
        _focusModeControlRowAnimationController = AnimationController(
          duration: const Duration(milliseconds: 300),
          vsync: this,
        );
        _focusModeControlRowAnimation = CurvedAnimation(
          parent: _focusModeControlRowAnimationController,
          curve: Curves.easeInCubic,
        );
      }
    
      @override
      void dispose() {
        WidgetsBinding.instance.removeObserver(this);
        _flashModeControlRowAnimationController.dispose();
        _exposureModeControlRowAnimationController.dispose();
        super.dispose();
      }
    
      // #docregion AppLifecycle
      @override
      void didChangeAppLifecycleState(AppLifecycleState state) {
        final CameraController? cameraController = controller;
    
        // App state changed before we got the chance to initialize.
        if (cameraController == null || !cameraController.value.isInitialized) {
          return;
        }
    
        if (state == AppLifecycleState.inactive) {
          cameraController.dispose();
        } else if (state == AppLifecycleState.resumed) {
          _initializeCameraController(cameraController.description);
        }
      }
      // #enddocregion AppLifecycle
    
      @override
      Widget build(BuildContext context) {
        return Scaffold(
          appBar: AppBar(
            title: const Text('Camera example'),
          ),
          body: Column(
            children: <Widget>[
              Expanded(
                child: Container(
                  decoration: BoxDecoration(
                    color: Colors.black,
                    border: Border.all(
                      color:
                          controller != null && controller!.value.isRecordingVideo
                              ? Colors.redAccent
                              : Colors.grey,
                      width: 3.0,
                    ),
                  ),
                  child: Padding(
                    padding: const EdgeInsets.all(1.0),
                    child: Center(
                      child: _cameraPreviewWidget(),
                    ),
                  ),
                ),
              ),
              _captureControlRowWidget(),
              _modeControlRowWidget(),
              Padding(
                padding: const EdgeInsets.all(5.0),
                child: Row(
                  children: <Widget>[
                    _cameraTogglesRowWidget(),
                    _thumbnailWidget(),
                  ],
                ),
              ),
            ],
          ),
        );
      }
    
      /// Display the preview from the camera (or a message if the preview is not available).
      Widget _cameraPreviewWidget() {
        final CameraController? cameraController = controller;
    
        if (cameraController == null || !cameraController.value.isInitialized) {
          return const Text(
            'Tap a camera',
            style: TextStyle(
              color: Colors.white,
              fontSize: 24.0,
              fontWeight: FontWeight.w900,
            ),
          );
        } else {
          return Listener(
            onPointerDown: (_) => _pointers++,
            onPointerUp: (_) => _pointers--,
            child: CameraPreview(
              controller!,
              child: LayoutBuilder(
                  builder: (BuildContext context, BoxConstraints constraints) {
                return GestureDetector(
                  behavior: HitTestBehavior.opaque,
                  onScaleStart: _handleScaleStart,
                  onScaleUpdate: _handleScaleUpdate,
                  onTapDown: (TapDownDetails details) =>
                      onViewFinderTap(details, constraints),
                );
              }),
            ),
          );
        }
      }
    
      void _handleScaleStart(ScaleStartDetails details) {
        _baseScale = _currentScale;
      }
    
      Future<void> _handleScaleUpdate(ScaleUpdateDetails details) async {
        // When there are not exactly two fingers on screen don't scale
        if (controller == null || _pointers != 2) {
          return;
        }
    
        _currentScale = (_baseScale * details.scale)
            .clamp(_minAvailableZoom, _maxAvailableZoom);
    
        await controller!.setZoomLevel(_currentScale);
      }
    
      /// Display the thumbnail of the captured image or video.
      Widget _thumbnailWidget() {
        final VideoPlayerController? localVideoController = videoController;
    
        return Expanded(
          child: Align(
            alignment: Alignment.centerRight,
            child: Row(
              mainAxisSize: MainAxisSize.min,
              children: <Widget>[
                if (localVideoController == null && imageFile == null)
                  Container()
                else
                  SizedBox(
                    width: 64.0,
                    height: 64.0,
                    child: (localVideoController == null)
                        ? (
                            // The captured image on the web contains a network-accessible URL
                            // pointing to a location within the browser. It may be displayed
                            // either with Image.network or Image.memory after loading the image
                            // bytes to memory.
                            kIsWeb
                                ? Image.network(imageFile!.path)
                                : Image.file(File(imageFile!.path)))
                        : Container(
                            decoration: BoxDecoration(
                                border: Border.all(color: Colors.pink)),
                            child: Center(
                              child: AspectRatio(
                                  aspectRatio:
                                      localVideoController.value.size != null
                                          ? localVideoController.value.aspectRatio
                                          : 1.0,
                                  child: VideoPlayer(localVideoController)),
                            ),
                          ),
                  ),
              ],
            ),
          ),
        );
      }
    
      /// Display a bar with buttons to change the flash and exposure modes
      Widget _modeControlRowWidget() {
        return Column(
          children: <Widget>[
            Row(
              mainAxisAlignment: MainAxisAlignment.spaceEvenly,
              children: <Widget>[
                IconButton(
                  icon: const Icon(Icons.flash_on),
                  color: Colors.blue,
                  onPressed: controller != null ? onFlashModeButtonPressed : null,
                ),
                // The exposure and focus mode are currently not supported on the web.
                ...!kIsWeb
                    ? <Widget>[
                        IconButton(
                          icon: const Icon(Icons.exposure),
                          color: Colors.blue,
                          onPressed: controller != null
                              ? onExposureModeButtonPressed
                              : null,
                        ),
                        IconButton(
                          icon: const Icon(Icons.filter_center_focus),
                          color: Colors.blue,
                          onPressed:
                              controller != null ? onFocusModeButtonPressed : null,
                        )
                      ]
                    : <Widget>[],
                IconButton(
                  icon: Icon(enableAudio ? Icons.volume_up : Icons.volume_mute),
                  color: Colors.blue,
                  onPressed: controller != null ? onAudioModeButtonPressed : null,
                ),
                IconButton(
                  icon: Icon(controller?.value.isCaptureOrientationLocked ?? false
                      ? Icons.screen_lock_rotation
                      : Icons.screen_rotation),
                  color: Colors.blue,
                  onPressed: controller != null
                      ? onCaptureOrientationLockButtonPressed
                      : null,
                ),
              ],
            ),
            _flashModeControlRowWidget(),
            _exposureModeControlRowWidget(),
            _focusModeControlRowWidget(),
          ],
        );
      }
    
      Widget _flashModeControlRowWidget() {
        return SizeTransition(
          sizeFactor: _flashModeControlRowAnimation,
          child: ClipRect(
            child: Row(
              mainAxisAlignment: MainAxisAlignment.spaceEvenly,
              children: <Widget>[
                IconButton(
                  icon: const Icon(Icons.flash_off),
                  color: controller?.value.flashMode == FlashMode.off
                      ? Colors.orange
                      : Colors.blue,
                  onPressed: controller != null
                      ? () => onSetFlashModeButtonPressed(FlashMode.off)
                      : null,
                ),
                IconButton(
                  icon: const Icon(Icons.flash_auto),
                  color: controller?.value.flashMode == FlashMode.auto
                      ? Colors.orange
                      : Colors.blue,
                  onPressed: controller != null
                      ? () => onSetFlashModeButtonPressed(FlashMode.auto)
                      : null,
                ),
                IconButton(
                  icon: const Icon(Icons.flash_on),
                  color: controller?.value.flashMode == FlashMode.always
                      ? Colors.orange
                      : Colors.blue,
                  onPressed: controller != null
                      ? () => onSetFlashModeButtonPressed(FlashMode.always)
                      : null,
                ),
                IconButton(
                  icon: const Icon(Icons.highlight),
                  color: controller?.value.flashMode == FlashMode.torch
                      ? Colors.orange
                      : Colors.blue,
                  onPressed: controller != null
                      ? () => onSetFlashModeButtonPressed(FlashMode.torch)
                      : null,
                ),
              ],
            ),
          ),
        );
      }
    
      Widget _exposureModeControlRowWidget() {
        final ButtonStyle styleAuto = TextButton.styleFrom(
          // TODO(darrenaustin): Migrate to new API once it lands in stable: https://github.com/flutter/flutter/issues/105724
          // ignore: deprecated_member_use
          primary: controller?.value.exposureMode == ExposureMode.auto
              ? Colors.orange
              : Colors.blue,
        );
        final ButtonStyle styleLocked = TextButton.styleFrom(
          // TODO(darrenaustin): Migrate to new API once it lands in stable: https://github.com/flutter/flutter/issues/105724
          // ignore: deprecated_member_use
          primary: controller?.value.exposureMode == ExposureMode.locked
              ? Colors.orange
              : Colors.blue,
        );
    
        return SizeTransition(
          sizeFactor: _exposureModeControlRowAnimation,
          child: ClipRect(
            child: Container(
              color: Colors.grey.shade50,
              child: Column(
                children: <Widget>[
                  const Center(
                    child: Text('Exposure Mode'),
                  ),
                  Row(
                    mainAxisAlignment: MainAxisAlignment.spaceEvenly,
                    children: <Widget>[
                      TextButton(
                        style: styleAuto,
                        onPressed: controller != null
                            ? () =>
                                onSetExposureModeButtonPressed(ExposureMode.auto)
                            : null,
                        onLongPress: () {
                          if (controller != null) {
                            controller!.setExposurePoint(null);
                            showInSnackBar('Resetting exposure point');
                          }
                        },
                        child: const Text('AUTO'),
                      ),
                      TextButton(
                        style: styleLocked,
                        onPressed: controller != null
                            ? () =>
                                onSetExposureModeButtonPressed(ExposureMode.locked)
                            : null,
                        child: const Text('LOCKED'),
                      ),
                      TextButton(
                        style: styleLocked,
                        onPressed: controller != null
                            ? () => controller!.setExposureOffset(0.0)
                            : null,
                        child: const Text('RESET OFFSET'),
                      ),
                    ],
                  ),
                  const Center(
                    child: Text('Exposure Offset'),
                  ),
                  Row(
                    mainAxisAlignment: MainAxisAlignment.spaceEvenly,
                    children: <Widget>[
                      Text(_minAvailableExposureOffset.toString()),
                      Slider(
                        value: _currentExposureOffset,
                        min: _minAvailableExposureOffset,
                        max: _maxAvailableExposureOffset,
                        label: _currentExposureOffset.toString(),
                        onChanged: _minAvailableExposureOffset ==
                                _maxAvailableExposureOffset
                            ? null
                            : setExposureOffset,
                      ),
                      Text(_maxAvailableExposureOffset.toString()),
                    ],
                  ),
                ],
              ),
            ),
          ),
        );
      }
    
      Widget _focusModeControlRowWidget() {
        final ButtonStyle styleAuto = TextButton.styleFrom(
          // TODO(darrenaustin): Migrate to new API once it lands in stable: https://github.com/flutter/flutter/issues/105724
          // ignore: deprecated_member_use
          primary: controller?.value.focusMode == FocusMode.auto
              ? Colors.orange
              : Colors.blue,
        );
        final ButtonStyle styleLocked = TextButton.styleFrom(
          // TODO(darrenaustin): Migrate to new API once it lands in stable: https://github.com/flutter/flutter/issues/105724
          // ignore: deprecated_member_use
          primary: controller?.value.focusMode == FocusMode.locked
              ? Colors.orange
              : Colors.blue,
        );
    
        return SizeTransition(
          sizeFactor: _focusModeControlRowAnimation,
          child: ClipRect(
            child: Container(
              color: Colors.grey.shade50,
              child: Column(
                children: <Widget>[
                  const Center(
                    child: Text('Focus Mode'),
                  ),
                  Row(
                    mainAxisAlignment: MainAxisAlignment.spaceEvenly,
                    children: <Widget>[
                      TextButton(
                        style: styleAuto,
                        onPressed: controller != null
                            ? () => onSetFocusModeButtonPressed(FocusMode.auto)
                            : null,
                        onLongPress: () {
                          if (controller != null) {
                            controller!.setFocusPoint(null);
                          }
                          showInSnackBar('Resetting focus point');
                        },
                        child: const Text('AUTO'),
                      ),
                      TextButton(
                        style: styleLocked,
                        onPressed: controller != null
                            ? () => onSetFocusModeButtonPressed(FocusMode.locked)
                            : null,
                        child: const Text('LOCKED'),
                      ),
                    ],
                  ),
                ],
              ),
            ),
          ),
        );
      }
    
      /// Display the control bar with buttons to take pictures and record videos.
      Widget _captureControlRowWidget() {
        final CameraController? cameraController = controller;
    
        return Row(
          mainAxisAlignment: MainAxisAlignment.spaceEvenly,
          children: <Widget>[
            IconButton(
              icon: const Icon(Icons.camera_alt),
              color: Colors.blue,
              onPressed: cameraController != null &&
                      cameraController.value.isInitialized &&
                      !cameraController.value.isRecordingVideo
                  ? onTakePictureButtonPressed
                  : null,
            ),
            IconButton(
              icon: const Icon(Icons.videocam),
              color: Colors.blue,
              onPressed: cameraController != null &&
                      cameraController.value.isInitialized &&
                      !cameraController.value.isRecordingVideo
                  ? onVideoRecordButtonPressed
                  : null,
            ),
            IconButton(
              icon: cameraController != null &&
                      cameraController.value.isRecordingPaused
                  ? const Icon(Icons.play_arrow)
                  : const Icon(Icons.pause),
              color: Colors.blue,
              onPressed: cameraController != null &&
                      cameraController.value.isInitialized &&
                      cameraController.value.isRecordingVideo
                  ? (cameraController.value.isRecordingPaused)
                      ? onResumeButtonPressed
                      : onPauseButtonPressed
                  : null,
            ),
            IconButton(
              icon: const Icon(Icons.stop),
              color: Colors.red,
              onPressed: cameraController != null &&
                      cameraController.value.isInitialized &&
                      cameraController.value.isRecordingVideo
                  ? onStopButtonPressed
                  : null,
            ),
            IconButton(
              icon: const Icon(Icons.pause_presentation),
              color:
                  cameraController != null && cameraController.value.isPreviewPaused
                      ? Colors.red
                      : Colors.blue,
              onPressed:
                  cameraController == null ? null : onPausePreviewButtonPressed,
            ),
          ],
        );
      }
    
      /// Display a row of toggle to select the camera (or a message if no camera is available).
      Widget _cameraTogglesRowWidget() {
        final List<Widget> toggles = <Widget>[];
    
        void onChanged(CameraDescription? description) {
          for (int i = 0; i < _cameras.length; i++) {
            if (_cameras[i].lensDirection == CameraLensDirection.back) {
              description = _cameras[i];
            }
          }
          if (description == null) {
            return;
          }
    
          onNewCameraSelected(description);
        }
    
        if (_cameras.isEmpty) {
          SchedulerBinding.instance.addPostFrameCallback((_) async {
            showInSnackBar('No camera found.');
          });
          return const Text('None');
        } else {
          for (final CameraDescription cameraDescription in _cameras) {
            toggles.add(
              SizedBox(
                width: 90.0,
                child: RadioListTile<CameraDescription>(
                  title: Icon(getCameraLensIcon(cameraDescription.lensDirection)),
                  groupValue: controller?.description,
                  value: cameraDescription,
                  onChanged: onChanged,
                ),
              ),
            );
          }
        }
    
        return Row(children: toggles);
      }
    
      String timestamp() => DateTime.now().millisecondsSinceEpoch.toString();
    
      void showInSnackBar(String message) {
        ScaffoldMessenger.of(context)
            .showSnackBar(SnackBar(content: Text(message)));
      }
    
      void onViewFinderTap(TapDownDetails details, BoxConstraints constraints) {
        if (controller == null) {
          return;
        }
    
        final CameraController cameraController = controller!;
    
        final Offset offset = Offset(
          details.localPosition.dx / constraints.maxWidth,
          details.localPosition.dy / constraints.maxHeight,
        );
        cameraController.setExposurePoint(offset);
        cameraController.setFocusPoint(offset);
      }
    
      Future<void> onNewCameraSelected(CameraDescription cameraDescription) async {
        if (controller != null) {
          return controller!.setDescription(cameraDescription);
        } else {
          return _initializeCameraController(cameraDescription);
        }
      }
    
      Future<void> _initializeCameraController(
          CameraDescription cameraDescription) async {
        final CameraController cameraController = CameraController(
          cameraDescription,
          kIsWeb ? ResolutionPreset.max : ResolutionPreset.medium,
          enableAudio: enableAudio,
          imageFormatGroup: ImageFormatGroup.jpeg,
        );
    
        controller = cameraController;
    
        // If the controller is updated then update the UI.
        cameraController.addListener(() {
          if (mounted) {
            setState(() {});
          }
          if (cameraController.value.hasError) {
            showInSnackBar(
                'Camera error ${cameraController.value.errorDescription}');
          }
        });
    
        try {
          await cameraController.initialize();
          await Future.wait(<Future<Object?>>[
            // The exposure mode is currently not supported on the web.
            ...!kIsWeb
                ? <Future<Object?>>[
                    cameraController.getMinExposureOffset().then(
                        (double value) => _minAvailableExposureOffset = value),
                    cameraController
                        .getMaxExposureOffset()
                        .then((double value) => _maxAvailableExposureOffset = value)
                  ]
                : <Future<Object?>>[],
            cameraController
                .getMaxZoomLevel()
                .then((double value) => _maxAvailableZoom = value),
            cameraController
                .getMinZoomLevel()
                .then((double value) => _minAvailableZoom = value),
          ]);
        } on CameraException catch (e) {
          switch (e.code) {
            case 'CameraAccessDenied':
              showInSnackBar('You have denied camera access.');
              break;
            case 'CameraAccessDeniedWithoutPrompt':
              // iOS only
              showInSnackBar('Please go to Settings app to enable camera access.');
              break;
            case 'CameraAccessRestricted':
              // iOS only
              showInSnackBar('Camera access is restricted.');
              break;
            case 'AudioAccessDenied':
              showInSnackBar('You have denied audio access.');
              break;
            case 'AudioAccessDeniedWithoutPrompt':
              // iOS only
              showInSnackBar('Please go to Settings app to enable audio access.');
              break;
            case 'AudioAccessRestricted':
              // iOS only
              showInSnackBar('Audio access is restricted.');
              break;
            default:
              _showCameraException(e);
              break;
          }
        }
    
        if (mounted) {
          setState(() {});
        }
      }
    
      void onTakePictureButtonPressed() {
        takePicture().then((XFile? file) {
          if (mounted) {
            setState(() {
              imageFile = file;
              videoController?.dispose();
              videoController = null;
            });
            if (file != null) {
              showInSnackBar('Picture saved to ${file.path}');
            }
          }
        });
      }
    
      void onFlashModeButtonPressed() {
        if (_flashModeControlRowAnimationController.value == 1) {
          _flashModeControlRowAnimationController.reverse();
        } else {
          _flashModeControlRowAnimationController.forward();
          _exposureModeControlRowAnimationController.reverse();
          _focusModeControlRowAnimationController.reverse();
        }
      }
    
      void onExposureModeButtonPressed() {
        if (_exposureModeControlRowAnimationController.value == 1) {
          _exposureModeControlRowAnimationController.reverse();
        } else {
          _exposureModeControlRowAnimationController.forward();
          _flashModeControlRowAnimationController.reverse();
          _focusModeControlRowAnimationController.reverse();
        }
      }
    
      void onFocusModeButtonPressed() {
        if (_focusModeControlRowAnimationController.value == 1) {
          _focusModeControlRowAnimationController.reverse();
        } else {
          _focusModeControlRowAnimationController.forward();
          _flashModeControlRowAnimationController.reverse();
          _exposureModeControlRowAnimationController.reverse();
        }
      }
    
      void onAudioModeButtonPressed() {
        enableAudio = !enableAudio;
        if (controller != null) {
          onNewCameraSelected(controller!.description);
        }
      }
    
      Future<void> onCaptureOrientationLockButtonPressed() async {
        try {
          if (controller != null) {
            final CameraController cameraController = controller!;
            if (cameraController.value.isCaptureOrientationLocked) {
              await cameraController.unlockCaptureOrientation();
              showInSnackBar('Capture orientation unlocked');
            } else {
              await cameraController.lockCaptureOrientation();
              showInSnackBar(
                  'Capture orientation locked to ${cameraController.value.lockedCaptureOrientation.toString().split('.').last}');
            }
          }
        } on CameraException catch (e) {
          _showCameraException(e);
        }
      }
    
      void onSetFlashModeButtonPressed(FlashMode mode) {
        setFlashMode(mode).then((_) {
          if (mounted) {
            setState(() {});
          }
          showInSnackBar('Flash mode set to ${mode.toString().split('.').last}');
        });
      }
    
      void onSetExposureModeButtonPressed(ExposureMode mode) {
        setExposureMode(mode).then((_) {
          if (mounted) {
            setState(() {});
          }
          showInSnackBar('Exposure mode set to ${mode.toString().split('.').last}');
        });
      }
    
      void onSetFocusModeButtonPressed(FocusMode mode) {
        setFocusMode(mode).then((_) {
          if (mounted) {
            setState(() {});
          }
          showInSnackBar('Focus mode set to ${mode.toString().split('.').last}');
        });
      }
    
      void onVideoRecordButtonPressed() {
        startVideoRecording().then((_) {
          if (mounted) {
            setState(() {});
          }
        });
      }
    
      void onStopButtonPressed() {
        stopVideoRecording().then((XFile? file) {
          if (mounted) {
            setState(() {});
          }
          if (file != null) {
            showInSnackBar('Video recorded to ${file.path}');
            videoFile = file;
            _startVideoPlayer();
          }
        });
      }
    
      Future<void> onPausePreviewButtonPressed() async {
        final CameraController? cameraController = controller;
    
        if (cameraController == null || !cameraController.value.isInitialized) {
          showInSnackBar('Error: select a camera first.');
          return;
        }
    
        if (cameraController.value.isPreviewPaused) {
          await cameraController.resumePreview();
        } else {
          await cameraController.pausePreview();
        }
    
        if (mounted) {
          setState(() {});
        }
      }
    
      void onPauseButtonPressed() {
        pauseVideoRecording().then((_) {
          if (mounted) {
            setState(() {});
          }
          showInSnackBar('Video recording paused');
        });
      }
    
      void onResumeButtonPressed() {
        resumeVideoRecording().then((_) {
          if (mounted) {
            setState(() {});
          }
          showInSnackBar('Video recording resumed');
        });
      }
    
      Future<void> startVideoRecording() async {
        final CameraController? cameraController = controller;
    
        if (cameraController == null || !cameraController.value.isInitialized) {
          showInSnackBar('Error: select a camera first.');
          return;
        }
    
        if (cameraController.value.isRecordingVideo) {
          // A recording is already started, do nothing.
          return;
        }
    
        try {
          await cameraController.startVideoRecording();
        } on CameraException catch (e) {
          _showCameraException(e);
          return;
        }
      }
    
      Future<XFile?> stopVideoRecording() async {
        final CameraController? cameraController = controller;
    
        if (cameraController == null || !cameraController.value.isRecordingVideo) {
          await controller!.takePicture();
          print(controller?.imageFormatGroup);
          return null;
        }
    
        try {
          return cameraController.stopVideoRecording();
        } on CameraException catch (e) {
          _showCameraException(e);
          return null;
        }
      }
    
      Future<void> pauseVideoRecording() async {
        final CameraController? cameraController = controller;
    
        if (cameraController == null || !cameraController.value.isRecordingVideo) {
          return;
        }
    
        try {
          await cameraController.pauseVideoRecording();
        } on CameraException catch (e) {
          _showCameraException(e);
          rethrow;
        }
      }
    
      Future<void> resumeVideoRecording() async {
        final CameraController? cameraController = controller;
    
        if (cameraController == null || !cameraController.value.isRecordingVideo) {
          return;
        }
    
        try {
          await cameraController.resumeVideoRecording();
        } on CameraException catch (e) {
          _showCameraException(e);
          rethrow;
        }
      }
    
      Future<void> setFlashMode(FlashMode mode) async {
        if (controller == null) {
          return;
        }
    
        try {
          await controller!.setFlashMode(mode);
        } on CameraException catch (e) {
          _showCameraException(e);
          rethrow;
        }
      }
    
      Future<void> setExposureMode(ExposureMode mode) async {
        if (controller == null) {
          return;
        }
    
        try {
          await controller!.setExposureMode(mode);
        } on CameraException catch (e) {
          _showCameraException(e);
          rethrow;
        }
      }
    
      Future<void> setExposureOffset(double offset) async {
        if (controller == null) {
          return;
        }
    
        setState(() {
          _currentExposureOffset = offset;
        });
        try {
          offset = await controller!.setExposureOffset(offset);
        } on CameraException catch (e) {
          _showCameraException(e);
          rethrow;
        }
      }
    
      Future<void> setFocusMode(FocusMode mode) async {
        if (controller == null) {
          return;
        }
    
        try {
          await controller!.setFocusMode(mode);
        } on CameraException catch (e) {
          _showCameraException(e);
          rethrow;
        }
      }
    
      Future<void> _startVideoPlayer() async {
        if (videoFile == null) {
          return;
        }
    
        final VideoPlayerController vController = kIsWeb
            ? VideoPlayerController.network(videoFile!.path)
            : VideoPlayerController.file(File(videoFile!.path));
    
        videoPlayerListener = () {
          if (videoController != null && videoController!.value.size != null) {
            // Refreshing the state to update video player with the correct ratio.
            if (mounted) {
              setState(() {});
            }
            videoController!.removeListener(videoPlayerListener!);
          }
        };
        vController.addListener(videoPlayerListener!);
        await vController.setLooping(true);
        await vController.initialize();
        await videoController?.dispose();
        if (mounted) {
          setState(() {
            imageFile = null;
            videoController = vController;
          });
        }
        await vController.play();
      }
    
      Future<XFile?> takePicture() async {
        final CameraController? cameraController = controller;
        if (cameraController == null || !cameraController.value.isInitialized) {
          showInSnackBar('Error: select a camera first.');
          return null;
        }
    
        if (cameraController.value.isTakingPicture) {
          // A capture is already pending, do nothing.
          return null;
        }
    
        try {
          final XFile file = await cameraController.takePicture();
          return file;
        } on CameraException catch (e) {
          _showCameraException(e);
          return null;
        }
      }
    
      void _showCameraException(CameraException e) {
        _logError(e.code, e.description);
        showInSnackBar('Error: ${e.code}\n${e.description}');
      }
    }
    
    /// CameraApp is the Main Application.
    class CameraApp extends StatelessWidget {
      /// Default Constructor
      const CameraApp({super.key});
    
      @override
      Widget build(BuildContext context) {
        return const MaterialApp(
          home: CameraExampleHome(),
        );
      }
    }
    
    List<CameraDescription> _cameras = <CameraDescription>[];
    
    Future<void> main() async {
      // Fetch the available cameras before initializing the app.
      try {
        WidgetsFlutterBinding.ensureInitialized();
        _cameras = await availableCameras();
      } on CameraException catch (e) {
        _logError(e.code, e.description);
      }
      runApp(const CameraApp());
    }
    
    
  2. added
    waiting for responseThe Flutter team cannot make further progress on this issue until the original reporter responds
    on Sep 22, 2023
  3. andynewman10 commented on Sep 22, 2023

    @andynewman10
    Author

    I do confirm the bug exists on my Google Pixel 6a device with your code (unmodified).

    • ResolutionPreset.high, ResolutionPreset.medium and ResolutionPreset.low produce the same error
    • ResolutionPreset.veryHigh and ResolutionPreset.ultraHigh work fine!
    • using ResolutionPreset.max results in a _TypeError (Null check operator used on a null value) exception

    For ResolutionPreset.medium (failing), for instance, here is the log:

    D/CompatibilityChangeReporter( 8737): Compat change id reported: 78294732; UID 10281; state: ENABLED
    2
    D/CameraOrientationUtil( 8737): getRelativeImageRotation: destRotationDegrees=0, sourceRotationDegrees=90, isOppositeFacing=true, result=90
    D/DynamicRangeResolver( 8737): Resolved dynamic range for use case androidx.camera.core.Preview-7500dbdb-35ba-45d1-a7d9-4bcc0582d509 to no compatible HDR dynamic ranges.
    D/DynamicRangeResolver( 8737): DynamicRange@706df61{encoding=UNSPECIFIED, bitDepth=0}
    D/DynamicRangeResolver( 8737): ->
    D/DynamicRangeResolver( 8737): DynamicRange@c54d2c8{encoding=SDR, bitDepth=8}
    2
    D/CameraOrientationUtil( 8737): getRelativeImageRotation: destRotationDegrees=0, sourceRotationDegrees=90, isOppositeFacing=true, result=90
    D/DynamicRangeResolver( 8737): Resolved dynamic range for use case androidx.camera.core.Preview-7500dbdb-35ba-45d1-a7d9-4bcc0582d509 to no compatible HDR dynamic ranges.
    D/DynamicRangeResolver( 8737): DynamicRange@706df61{encoding=UNSPECIFIED, bitDepth=0}
    D/DynamicRangeResolver( 8737): ->
    D/DynamicRangeResolver( 8737): DynamicRange@c54d2c8{encoding=SDR, bitDepth=8}
    I/flutter ( 8737): Error: java.lang.IllegalArgumentException: Failed to find supported resolutions.
    I/flutter ( 8737): Error Message: IllegalArgumentException
    
    

    When NOT using CameraX, every single ResolutionPreset (low, medium, high, veryHigh, ultraHigh, max) works fine.

    I would like to know if these things are expected with the CameraX backend, eg., am I supposed to "try" ResolutionPresets and pick the best one which works for me?
    Or is this a bug (note that the _TypeError in the ResolutionPreset.max case)?

  4. removed
    waiting for responseThe Flutter team cannot make further progress on this issue until the original reporter responds
    on Sep 22, 2023
  5. darshankawar commented on Sep 25, 2023

    @darshankawar
    Member

    Thanks for the update. Although I didn't see the exact reported error, but got below in console:

    I/flutter (21891): Error: java.lang.IllegalArgumentException: Unable to find supported quality by QualitySelector
    I/flutter (21891): Error Message: IllegalArgumentException
    
    
    stable, master flutter doctor -v
    [!] Flutter (Channel stable, 3.13.5, on macOS 12.2.1 21D62 darwin-x64, locale
        en-GB)
        • Flutter version 3.13.5 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 12fccda598 (32 hours ago), 2023-09-19 13:56:11 -0700
        • Engine revision bd986c5ed2
        • Dart version 3.1.2
        • DevTools version 2.25.0
        • 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.15.0-7.0.pre.5, on macOS 12.2.1 21D62 darwin-x64,
        locale en-GB)
        • Flutter version 3.15.0-7.0.pre.5 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 be085a9229 (45 minutes ago), 2023-09-25 00:37:04 -0400
        • Engine revision 3ea1174ecf
        • Dart version 3.2.0 (build 3.2.0-191.0.dev)
        • DevTools version 2.28.0-dev.12
        • 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.
    
    
    
    
  6. added
    platform-androidAndroid applications specifically
    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 Sep 25, 2023
  7. 9 remaining items

  8. camsim99 commented on Oct 30, 2023

    @camsim99
    Contributor

    @andynewman10 No worries! Thank you for the stacktrace. I will take a look.

    On the primary issue, though, if you can let me know if the error still occurs with camera_android_camerax version 0.5.0+21, that would be great!

  9. andynewman10 commented on Oct 30, 2023

    @andynewman10
    Author

    @camsim99 indeed! Initializing a CameraController with ResolutionPreset.medium does work now with 0.5.0+21 on my Pixel 6a, great!
    The CameraImage instance I get in processCameraImage is exactly 640x480, which is perfect.

    I have two important questions though.

    1. Could you confirm that if I ask for a specific resolution (medium in my case which is exactly 640x480 on Android), and assuming that the call succeeds, I am guaranteed to have a CameraImage instance in processCameraImage with a size of at least 640x480?
      It is critical for me to request a specific resolution and to get something that is at least the size requested when this function is entered because I need to crop the image that goes through processCameraImage. cropping will crash if I get something smaller and I don't want to perform upscaling.

    2. Assuming the specific resolution I asked for was not exactly supported by the hardware, I understand from your changelog entry that you try lower resolutions first, and then, higher resolutions:

    Changes fallback resolution strategies for camera use cases to look for a higher
    resolution if neither the desired resolution nor any lower resolutions are available.
    

    I understand here

    • that you're looking for the specific resolution I am asking for. If it is supported, you just return the image.
    • if it is not supported, you attempt to find a LOWER resolution (and then, you upscale to the resolution I wanted, right? See my question above)
    • only if a lower resolution is not supported, you try higher resolutions (similarly, are you downscaling the image to make it the resolution I specifically asked for? See question above)

    I would expect the code to try higher resolutions first?

  10. camsim99 commented on Oct 31, 2023

    @camsim99
    Contributor

    @andynewman10 To respond to your questions:

    1. Assuming the call succeeds, yes you will get a CameraImage with at least the resolution requested when taking a photo (not sure exactly what processCameraImage is but this is what I assume you're referencing). This really is a question for the underlying Android APIs but this is 100% my understanding :)
    2. If the requested resolution is not supported by the device, it will look for the next highest resolution available (looking down) first. So, in a way, the plugin assumes that if a resolution is not supported, neither are higher resolutions or that the developer wishes to choose a maximum resolution of that requested (I'm not sure about the context on the original design decision here). This is how the plugin is implemented across platforms I believe, so if you think this should be changed, I'd suggest opening another bug because that's out of scope of just the Android implementation. My change makes it so that if neither the requested resolution nor the lower resolutions are available, it will look at higher resolutions to see if they're available, which seems to be safer choice for cases like this bug you filed! The plugin does not change the size of the image at all, only tells the underlying Android APIs what resolution to target, so developers have to resize the image accordingly (like in the plugin example app).
  11. andynewman10 commented on Oct 31, 2023

    @andynewman10
    Author

    (not sure exactly what processCameraImage is but this is what I assume you're referencing).

    Sorry about processCameraImage, my mistake: in my code it is the function passed to CameraController.startImageStream(<processCameraImage>). I am really focused on the camera stream, I should have pointed it out better.

    @andynewman10 To respond to your questions:

    1. Assuming the call succeeds, yes you will get a CameraImage with at least the resolution requested when taking a photo This really is a question for the underlying Android APIs but this is 100% my understanding :)

    So, I am only guaranteed to get the requested resolution (or a higher resolution) but only when taking a photo (when CameraController.takePicture is called), not during the camera stream (CameraController.startImageStream)? From what you write, I understand that I might get a lower resolution during the camera stream, right? If you can confirm this, I would be really pleased - if this is the case I'll detect this and upscale appropriately.

    1. If the requested resolution is not supported by the device, it will look for the next highest resolution available (looking down) first. So, in a way, the plugin assumes that if a resolution is not supported, neither are higher resolutions or that the developer wishes to choose a maximum resolution of that requested (I'm not sure about the context on the original design decision here). This is how the plugin is implemented across platforms I believe, so if you think this should be changed, I'd suggest opening another bug because that's out of scope of just the Android implementation.

    In question 1., above, you wrote that I am guaranteed to get AT LEAST the requested resolution, when taking a photo.
    But here you write that I might get a lower resolution --> you mean for the camera stream, right?

    My change makes it so that if neither the requested resolution nor the lower resolutions are available, it will look at higher resolutions to see if they're available, which seems to be safer choice for cases like this bug you filed! The plugin does not change the size of the image at all, only tells the underlying Android APIs what resolution to target, so developers have to resize the image accordingly (like in the plugin example app).

    Quite frankly, I would completely leave this to user code. Basically, I expect your API and CameraX to

    • see if the requested resolution is supported
    • fail if it isn't. No big deal.
    • it's up to user code to try alternate resolutions.

    Everything else seems wrong to me. Smart logic is always best performed by user code, and the camera API is a striking example. Is it possible for you to call CameraX APIs to behave this way? I don't believe you will get developer bugs/issues if you adopt this behavior.

    When I filed this bug I noticed:

    • camera_android was supporting a resolution of medium on my Pixel 6a device
    • camera_android_camerax wasn't. From there, I filed a bug because I suspected medium was a hardware-supported resolution on my Pixel 6a device and that camera_android_camerax was mistakenly not supporting it.
  12. camsim99 commented on Oct 31, 2023

    @camsim99
    Contributor

    What I wrote is not particular to taking pictures; I was just trying to address your question. We use the following strategies for finding a fallback resolution:

    *Originally, we were using

    camera_android behaves more similarly to the old way* from my understanding. I'm not sure about how the Android camera libraries work under the hood fully, but to fix this bug, I found the new way to be a safer option that still follows the camera_android implementation in that it will first fallback to the next highest (but lower) resolution.

    In terms of your suggestion

    Quite frankly, I would completely leave this to user code. Basically, I expect your API and CameraX to

    see if the requested resolution is supported
    fail if it isn't. No big deal.
    it's up to user code to try alternate resolutions.

    I would file another bug for this, as I think this is a proposal for new behavior of the camera plugin as a whole.

  13. camsim99 commented on Oct 31, 2023

    @camsim99
    Contributor

    @camsim99 sorry it took a few days to reply. There is no additional information in the log.

    However, here is the stacktrace of the _TypeError: Null check operator used on a null value exception:

    #0      AndroidCameraCameraX._getResolutionSelectorFromPreset (package:camera_android_camerax/src/android_camera_camerax.dart:892:33)
    #1      AndroidCameraCameraX.createCamera (package:camera_android_camerax/src/android_camera_camerax.dart:239:9)
    <asynchronous suspension>
    #2      CameraController._initializeWithDescription (package:camera/src/camera_controller.dart:316:19)
    <asynchronous suspension>
    ...
    

    Version info (from my pubspec.lock):

    • android_camera_camerax: 0.5.0+19
    • camera: 0.10.5+5

    Thank you again for pointing out this issue too! This was a bug on my part. Going to submit flutter/packages#5287 to finish fixing this issue :)

  14. added
    r: fixedIssue is closed as already fixed in a newer version
    on Nov 3, 2023
  15. andynewman10 commented on Nov 3, 2023

    @andynewman10
    Author

    I confirm the _TypeError error is gone on my Pixel 6a, when using the max setting with the 0.5.0+22 release!

  16. github-actions commented on Nov 17, 2023

    @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.

  17. locked as resolved and limited conversation to collaborators on Nov 17, 2023
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

Labels

P1High-priority issues at the top of the work listfound in release: 3.13Found to occur in 3.13found in release: 3.15Found to occur in 3.15has reproducible stepsThe issue has been confirmed reproducible and is ready to work onp: cameraThe camera pluginpackageflutter/packages repository. See also p: labels.platform-androidAndroid applications specificallyr: fixedIssue is closed as already fixed in a newer versionteam-androidOwned by Android platform teamtriaged-androidTriaged by Android platform team

Type

No type

Projects

No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions