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

[camera] Android 13 crash when initializing camera #109769

Closed
shliama opened this issue Aug 18, 2022 · 137 comments · Fixed by flutter/plugins#7073 or flutter/packages#4635
Closed

[camera] Android 13 crash when initializing camera #109769

shliama opened this issue Aug 18, 2022 · 137 comments · Fixed by flutter/plugins#7073 or flutter/packages#4635
Assignees
Labels
c: crash Stack traces logged to the console c: fatal crash Crashes that terminate the process customer: crowd Affects or could affect many people, though not necessarily a specific customer. e: OS-version specific Affects only some versions of the relevant operating system found in release: 3.1 Found to occur in 3.1 has reproducible steps The issue has been confirmed reproducible and is ready to work on p: camera The camera plugin P1 High-priority issues at the top of the work list package flutter/packages repository. See also p: labels. platform-android Android applications specifically

Comments

@shliama
Copy link

shliama commented Aug 18, 2022

Steps to Reproduce

  1. Bump compileSdkVersion & targetSdkVersion to 33
  2. Run camera plugin example app on a device or emulator with Android 13
  3. Get a crash when initializing camera (as soon as Camera permissions are accepted)

java.lang.NullPointerException: Attempt to invoke virtual method 'int android.media.EncoderProfiles$VideoProfile.getWidth()' on a null object reference

Reproducible with the plugin example app, here is a fork of the plugin repository with a single commit, that just bumps compileSdkVersion & targetSdkVersion to 33

shliama/plugins@b9fa432

Expected results:
No crash & camera preview

Actual results:
Crash

Code sample
Reproducible with the plugin example app, here is a fork of the plugin repository with a single commit, that just bumps compileSdkVersion & targetSdkVersion to 33

https://github.com/shliama/plugins/commit/b9fa432b7c60cb021c28002673d55838d6377506
Logs
√  Built build\app\outputs\flutter-apk\app-debug.apk.
Installing build\app\outputs\flutter-apk\app.apk...
Debug service listening on ws://127.0.0.1:50570/QMiwEXsdw3Y=/ws
Syncing files to device Pixel 4a 5G...
E/SurfaceSyncer( 7292): Failed to find sync for id=0
W/Parcel  ( 7292): Expecting binder but got null!
D/CompatibilityChangeReporter( 7292): Compat change id reported: 78294732; UID 10048; state: ENABLED
D/CompatibilityChangeReporter( 7292): Compat change id reported: 206033068; UID 10048; state: ENABLED
D/AndroidRuntime( 7292): Shutting down VM
E/AndroidRuntime( 7292): FATAL EXCEPTION: main
E/AndroidRuntime( 7292): Process: io.flutter.plugins.cameraexample, PID: 7292
E/AndroidRuntime( 7292): java.lang.RuntimeException: Failure delivering result ResultInfo{who=@android:requestPermissions:, request=9796, result=-1, data=Intent { act=android.content.pm.action.REQUEST_PERMISSIONS (has extras) }} to activity {io.flutter.plugins.cameraexample/io.flutter.embedding.android.FlutterActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'int android.media.EncoderProfiles$VideoProfile.getWidth()' on a null object reference
E/AndroidRuntime( 7292): 	at android.app.ActivityThread.deliverResults(ActivityThread.java:5347)
E/AndroidRuntime( 7292): 	at android.app.ActivityThread.handleSendResult(ActivityThread.java:5386)
E/AndroidRuntime( 7292): 	at android.app.servertransaction.ActivityResultItem.execute(ActivityResultItem.java:67)
E/AndroidRuntime( 7292): 	at android.app.servertransaction.ActivityTransactionItem.execute(ActivityTransactionItem.java:45)
E/AndroidRuntime( 7292): 	at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:135)
E/AndroidRuntime( 7292): 	at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:95)
E/AndroidRuntime( 7292): 	at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2308)
E/AndroidRuntime( 7292): 	at android.os.Handler.dispatchMessage(Handler.java:106)
E/AndroidRuntime( 7292): 	at android.os.Looper.loopOnce(Looper.java:201)
E/AndroidRuntime( 7292): 	at android.os.Looper.loop(Looper.java:288)
E/AndroidRuntime( 7292): 	at android.app.ActivityThread.main(ActivityThread.java:7898)
E/AndroidRuntime( 7292): 	at java.lang.reflect.Method.invoke(Native Method)
E/AndroidRuntime( 7292): 	at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:548)
E/AndroidRuntime( 7292): 	at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:936)
E/AndroidRuntime( 7292): Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'int android.media.EncoderProfiles$VideoProfile.getWidth()' on a null object reference
E/AndroidRuntime( 7292): 	at io.flutter.plugins.camera.features.resolution.ResolutionFeature.configureResolution(ResolutionFeature.java:244)
E/AndroidRuntime( 7292): 	at io.flutter.plugins.camera.features.resolution.ResolutionFeature.<init>(ResolutionFeature.java:50)
E/AndroidRuntime( 7292): 	at io.flutter.plugins.camera.features.CameraFeatureFactoryImpl.createResolutionFeature(CameraFeatureFactoryImpl.java:58)
E/AndroidRuntime( 7292): 	at io.flutter.plugins.camera.features.CameraFeatures.init(CameraFeatures.java:71)
E/AndroidRuntime( 7292): 	at io.flutter.plugins.camera.Camera.<init>(Camera.java:217)
E/AndroidRuntime( 7292): 	at io.flutter.plugins.camera.MethodCallHandlerImpl.instantiateCamera(MethodCallHandlerImpl.java:386)
E/AndroidRuntime( 7292): 	at io.flutter.plugins.camera.MethodCallHandlerImpl.lambda$onMethodCall$0$MethodCallHandlerImpl(MethodCallHandlerImpl.java:81)
E/AndroidRuntime( 7292): 	at io.flutter.plugins.camera.-$$Lambda$MethodCallHandlerImpl$OMU5dV7VCKXKBT37_ThIybqlHuo.onResult(Unknown Source:6)
E/AndroidRuntime( 7292): 	at io.flutter.plugins.camera.CameraPermissions.lambda$requestPermissions$0$CameraPermissions(CameraPermissions.java:58)
E/AndroidRuntime( 7292): 	at io.flutter.plugins.camera.-$$Lambda$CameraPermissions$5yqyw-OpZZu-E824jQ34RA2nmFk.onResult(Unknown Source:4)
E/AndroidRuntime( 7292): 	at io.flutter.plugins.camera.CameraPermissions$CameraRequestPermissionsListener.onRequestPermissionsResult(CameraPermissions.java:113)
E/AndroidRuntime( 7292): 	at io.flutter.embedding.engine.FlutterEngineConnectionRegistry$FlutterEngineActivityPluginBinding.onRequestPermissionsResult(FlutterEngineConnectionRegistry.java:777)
E/AndroidRuntime( 7292): 	at io.flutter.embedding.engine.FlutterEngineConnectionRegistry.onRequestPermissionsResult(FlutterEngineConnectionRegistry.java:409)
E/AndroidRuntime( 7292): 	at io.flutter.embedding.android.FlutterActivityAndFragmentDelegate.onRequestPermissionsResult(FlutterActivityAndFragmentDelegate.java:752)
E/AndroidRuntime( 7292): 	at io.flutter.embedding.android.FlutterActivity.onRequestPermissionsResult(FlutterActivity.java:748)
E/AndroidRuntime( 7292): 	at android.app.Activity.dispatchRequestPermissionsResult(Activity.java:8759)
E/AndroidRuntime( 7292): 	at android.app.Activity.dispatchActivityResult(Activity.java:8617)
E/AndroidRuntime( 7292): 	at android.app.ActivityThread.deliverResults(ActivityThread.java:5340)
E/AndroidRuntime( 7292): 	... 13 more
I/Process ( 7292): Sending signal. PID: 7292 SIG: 9
Lost connection to device.

@exaby73 exaby73 added the in triage Presently being triaged by the triage team label Aug 18, 2022
@exaby73
Copy link
Member

exaby73 commented Aug 18, 2022

For me, I can't seem to run the application. When the target and compile SDK is set to 32, the example works perfectly, but when I set it to 33, it doesn't. I am using a project generated by running flutter create then pasting the main.dart code into it and installing camera and video_player, instead of cloning the repo, running it on an Android Emulator. Are you able to run the example in this way?

Logs
[   +1 ms] Stopping app 'app.apk' on sdk gphone64 x86 64.
[        ] executing: C:\android-sdk\platform-tools\adb.exe -s emulator-5554 shell am force-stop com.example.issue_109769
[+1367 ms] executing: C:\android-sdk\platform-tools\adb.exe -s emulator-5554 shell pm list packages com.example.issue_109769
[ +171 ms] package:com.example.issue_109769
[   +1 ms] executing: C:\android-sdk\platform-tools\adb.exe -s emulator-5554 shell cat /data/local/tmp/sky.com.example.issue_109769.sha1
[ +122 ms] 7ed2af40651a743bece8bce3762c10c9080de65a
[        ] Installing APK.
Installing build\app\outputs\flutter-apk\app.apk...
[   +1 ms] executing: C:\android-sdk\platform-tools\adb.exe -s emulator-5554 install -t -r C:\Users\Nabeel Parkar\dev\nevercode\issue_109769\build\app\outputs\flutter-apk\app.apk
[+4133 ms] Performing Streamed Install
           Success
[   +1 ms] executing: C:\android-sdk\platform-tools\adb.exe -s emulator-5554 shell echo -n 4c226d793a7c2a8993874765878513f6a2d2b4b0 > /data/local/tmp/sky.com.example.issue_109769.sha1
[  +67 ms] executing: C:\android-sdk\platform-tools\adb.exe -s emulator-5554 shell -x logcat -v time -t 1
[ +166 ms] --------- beginning of system
           08-18 17:46:42.520 I/Telecom (  595): CarModeTracker: Package com.example.issue_109769 is not tracked.: SSH.oR@AJ4
[   +7 ms] executing: C:\android-sdk\platform-tools\adb.exe -s emulator-5554 shell am start -a android.intent.action.RUN -f 0x20000000 --ez enable-dart-profiling true --ez enable-checked-mode true --ez verify-entry-points true --ez start-paused true com.example.issue_109769/com.example.issue_109769.MainActivity
[ +147 ms] Starting: Intent { act=android.intent.action.RUN flg=0x20000000 cmp=com.example.issue_109769/.MainActivity (has extras) }

           Error type 3
           Error: Activity class {com.example.issue_109769/com.example.issue_109769.MainActivity} does not exist.
[        ] Waiting for observatory port to be available...
flutter doctor -v (Stable)
[✓] Flutter (Channel stable, 3.0.5, on Microsoft Windows [Version 10.0.22000.856], locale en-IN)
    • Flutter version 3.0.5 at C:\Users\Nabeel Parkar\fvm\versions\stable
    • Upstream repository https://github.com/flutter/flutter.git
    • Framework revision f1875d570e (5 weeks ago), 2022-07-13 11:24:16 -0700
    • Engine revision e85ea0e79c
    • Dart version 2.17.6
    • DevTools version 2.12.2

[✓] Android toolchain - develop for Android devices (Android SDK version 33.0.0)
    • Android SDK at C:\android-sdk
    • Platform android-33, build-tools 33.0.0
    • Java binary at: C:\Program Files\Android\Android Studio\jre\bin\java
    • Java version OpenJDK Runtime Environment (build 11.0.12+7-b1504.28-7817840)
    • All Android licenses accepted.

[✓] Chrome - develop for the web
    • CHROME_EXECUTABLE = C:\Program Files\BraveSoftware\Brave-Browser\Application\brave.exe

[✓] Visual Studio - develop for Windows (Visual Studio Community 2022 17.2.6)
    • Visual Studio at C:\Program Files\Microsoft Visual Studio\2022\Community
    • Visual Studio Community 2022 version 17.2.32630.192
    • Windows 10 SDK version 10.0.19041.0

[✓] Android Studio (version 2021.2)
    • Android Studio at C:\Program Files\Android\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.12+7-b1504.28-7817840)

[✓] IntelliJ IDEA Ultimate Edition (version 2022.2)
    • IntelliJ at C:\Program Files\JetBrains\IntelliJ IDEA 2022.2
    • Flutter plugin version 69.0.5
    • Dart plugin version 222.3739.24

[✓] VS Code (version 1.70.2)
    • VS Code at C:\Users\Nabeel Parkar\AppData\Local\Programs\Microsoft VS Code
    • Flutter extension version 3.46.0

[✓] Connected device (3 available)
    • Windows (desktop) • windows • windows-x64    • Microsoft Windows [Version 10.0.22000.856]
    • Chrome (web)      • chrome  • web-javascript • unknown
    • Edge (web)        • edge    • web-javascript • Microsoft Edge 104.0.1293.54

[✓] HTTP Host Availability
    • All required HTTP hosts are available

• No issues found!
flutter doctor -v (Master)
[✓] Flutter (Channel master, 3.1.0-0.0.pre.2346, on Microsoft Windows [Version 10.0.22000.856], locale en-IN)
    • Flutter version 3.1.0-0.0.pre.2346 on channel master at C:\Users\Nabeel Parkar\fvm\versions\master
    • Upstream repository https://github.com/flutter/flutter.git
    • Framework revision adda088bcc (4 hours ago), 2022-08-17 22:59:07 -0400
    • Engine revision a77ead45a8
    • Dart version 2.19.0 (build 2.19.0-108.0.dev)
    • DevTools version 2.16.0

[✓] Android toolchain - develop for Android devices (Android SDK version 33.0.0)
    • Android SDK at C:\android-sdk
    • Platform android-33, build-tools 33.0.0
    • Java binary at: C:\Program Files\Android\Android Studio\jre\bin\java
    • Java version OpenJDK Runtime Environment (build 11.0.12+7-b1504.28-7817840)
    • All Android licenses accepted.

[✓] Chrome - develop for the web
    • CHROME_EXECUTABLE = C:\Program Files\BraveSoftware\Brave-Browser\Application\brave.exe

[✓] Visual Studio - develop for Windows (Visual Studio Community 2022 17.2.6)
    • Visual Studio at C:\Program Files\Microsoft Visual Studio\2022\Community
    • Visual Studio Community 2022 version 17.2.32630.192
    • Windows 10 SDK version 10.0.19041.0

[✓] Android Studio (version 2021.2)
    • Android Studio at C:\Program Files\Android\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.12+7-b1504.28-7817840)

[✓] IntelliJ IDEA Ultimate Edition (version 2022.2)
    • IntelliJ at C:\Program Files\JetBrains\IntelliJ IDEA 2022.2
    • Flutter plugin version 69.0.5
    • Dart plugin version 222.3739.24

[✓] VS Code (version 1.70.2)
    • VS Code at C:\Users\Nabeel Parkar\AppData\Local\Programs\Microsoft VS Code
    • Flutter extension version 3.46.0

[✓] Connected device (3 available)
    • Windows (desktop) • windows • windows-x64    • Microsoft Windows [Version 10.0.22000.856]
    • Chrome (web)      • chrome  • web-javascript • unknown
    • Edge (web)        • edge    • web-javascript • Microsoft Edge 104.0.1293.54

[✓] HTTP Host Availability
    • All required HTTP hosts are available

• No issues found!

@exaby73 exaby73 added the waiting for customer response The Flutter team cannot make further progress on this issue until the original reporter responds label Aug 18, 2022
@shliama
Copy link
Author

shliama commented Aug 19, 2022

I created a new Flutter project following your steps, targeted Android 13 in build.gradle and copied main.dart from camera plugin example. I was able to build the project and run it on both virtual & physical devices (Android 13, API 33) and the crash is reproduced on both.

Here is the repository: https://github.com/shliama/camera_plugin_android_13_issue

Let me know if you need any specific info, but I don't run anything special - it is reproduced if you build the app on both Mac & Windows.

flutter doctor -v
[√] Flutter (Channel stable, 3.0.5, on Microsoft Windows [Version 10.0.22000.856], locale uk-UA)
    • Flutter version 3.0.5 at C:\Users\ASUS\Documents\flutter
    • Upstream repository https://github.com/flutter/flutter.git
    • Framework revision f1875d570e (5 weeks ago), 2022-07-13 11:24:16 -0700
    • Engine revision e85ea0e79c
    • Dart version 2.17.6
    • DevTools version 2.12.2

[√] Android toolchain - develop for Android devices (Android SDK version 33.0.0)
    • Android SDK at C:\Users\ASUS\AppData\Local\Android\sdk
    • Platform android-33, build-tools 33.0.0
    • Java binary at: C:\Program Files\Android\Android Studio\jre\bin\java
    • Java version OpenJDK Runtime Environment (build 11.0.12+7-b1504.28-7817840)
    • All Android licenses accepted.

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

[X] Visual Studio - develop for Windows
    X Visual Studio not installed; this is necessary for Windows development.
      Download at https://visualstudio.microsoft.com/downloads/.
      Please install the "Desktop development with C++" workload, including all of its default components

[√] Android Studio (version 2021.2)
    • Android Studio at C:\Program Files\Android\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.12+7-b1504.28-7817840)

[√] VS Code (version 1.69.2)
    • VS Code at C:\Users\ASUS\AppData\Local\Programs\Microsoft VS Code
    • Flutter extension version 3.29.0

[√] Connected device (5 available)
    • Pixel 4a 5G (mobile)         • 0A221JECB13605 • android-arm64  • Android 13 (API 33)
    • sdk gphone64 x86 64 (mobile) • emulator-5554  • android-x64    • Android 13 (API 33) (emulator)
    • Windows (desktop)            • windows        • windows-x64    • Microsoft Windows [Version 10.0.22000.856]
    • Chrome (web)                 • chrome         • web-javascript • Google Chrome 104.0.5112.101
    • Edge (web)                   • edge           • web-javascript • Microsoft Edge 104.0.1293.54

[√] HTTP Host Availability
    • All required HTTP hosts are available

! Doctor found issues in 1 category.

@github-actions github-actions bot removed the waiting for customer response The Flutter team cannot make further progress on this issue until the original reporter responds label Aug 19, 2022
@exaby73
Copy link
Member

exaby73 commented Aug 19, 2022

I cannot reproduce your issue due to the error I am facing. I'll label this issue either way for some insights from the team. Thank you

I can reproduce this issue on master. The issue I have described seems to be fixed in master. Below are the logs for the crash

Logs
[        ] Waiting for observatory port to be available...
[+2667 ms] Observatory URL on device: http://127.0.0.1:34521/tWhYrlnCBeQ=/
[        ] executing: C:\android-sdk\platform-tools\adb.exe -s emulator-5554 forward tcp:0 tcp:34521
[  +38 ms] 64265
[        ] Forwarded host port 64265 to device port 34521 for Observatory
[   +4 ms] Caching compiled dill
[  +28 ms] Connecting to service protocol: http://127.0.0.1:64265/tWhYrlnCBeQ=/
[ +368 ms] Launching a Dart Developer Service (DDS) instance at http://127.0.0.1:0, connecting to VM service at http://127.0.0.1:64265/tWhYrlnCBeQ=/.
[ +126 ms] DDS is listening at http://127.0.0.1:64268/n-WmffzobgU=/.
[  +39 ms] Successfully connected to service protocol: http://127.0.0.1:64265/tWhYrlnCBeQ=/
[  +41 ms] DevFS: Creating new filesystem on the device (null)
[  +20 ms] DevFS: Created new filesystem on the device (file:///data/user/0/com.example.issue_109769/code_cache/issue_109769RSNUON/issue_109769/)
[   +1 ms] Updating assets
Debug service listening on ws://127.0.0.1:64268/n-WmffzobgU=/ws
Syncing files to device sdk gphone64 x86 64...
[  +74 ms] Compiling dart to kernel with 0 updated files
[        ] Processing bundle.
[        ] <- recompile package:issue_109769/main.dart 93b5a9a8-cdcd-4c7f-9ec0-b5f1cf1a4b1b
[        ] <- 93b5a9a8-cdcd-4c7f-9ec0-b5f1cf1a4b1b
[   +1 ms] Bundle processing done.
[  +86 ms] Updating files.
[        ] DevFS: Sync finished
[        ] Synced 0.0MB.
[   +1 ms] <- accept
[   +5 ms] Connected to _flutterView/0x7e2a6ac6a110.
[ +541 ms] I/CameraManagerGlobal(19289): Connecting to camera service
[+1388 ms] E/SurfaceSyncer(19289): Failed to find sync for id=0
[ +186 ms] W/Parcel  (19289): Expecting binder but got null!
[+16137 ms] D/EGL_emulation(19289): app_time_stats: avg=5446.92ms min=10.36ms max=15965.22ms count=3
[+2454 ms] D/CompatibilityChangeReporter(19289): Compat change id reported: 78294732; UID 10162; state: ENABLED
[  +87 ms] D/CompatibilityChangeReporter(19289): Compat change id reported: 206033068; UID 10162; state: ENABLED
[   +9 ms] D/AndroidRuntime(19289): Shutting down VM
[  +31 ms] E/AndroidRuntime(19289): FATAL EXCEPTION: main
[        ] E/AndroidRuntime(19289): Process: com.example.issue_109769, PID: 19289
[        ] E/AndroidRuntime(19289): java.lang.RuntimeException: Failure delivering result ResultInfo{who=@android:requestPermissions:, request=9796, result=-1, data=Intent { act=android.content.pm.action.REQUEST_PERMISSIONS (has extras) }} to activity {com.example.issue_109769/com.example.issue_109769.MainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'int android.media.EncoderProfiles$VideoProfile.getWidth()' on a null object reference
[        ] E/AndroidRuntime(19289): 	at android.app.ActivityThread.deliverResults(ActivityThread.java:5347)
[        ] E/AndroidRuntime(19289): 	at android.app.ActivityThread.handleSendResult(ActivityThread.java:5386)
[        ] E/AndroidRuntime(19289): 	at android.app.servertransaction.ActivityResultItem.execute(ActivityResultItem.java:67)
[        ] E/AndroidRuntime(19289): 	at android.app.servertransaction.ActivityTransactionItem.execute(ActivityTransactionItem.java:45)
[        ] E/AndroidRuntime(19289): 	at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:135)
[        ] E/AndroidRuntime(19289): 	at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:95)
[        ] E/AndroidRuntime(19289): 	at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2308)
[        ] E/AndroidRuntime(19289): 	at android.os.Handler.dispatchMessage(Handler.java:106)
[        ] E/AndroidRuntime(19289): 	at android.os.Looper.loopOnce(Looper.java:201)
[        ] E/AndroidRuntime(19289): 	at android.os.Looper.loop(Looper.java:288)
[        ] E/AndroidRuntime(19289): 	at android.app.ActivityThread.main(ActivityThread.java:7898)
[        ] E/AndroidRuntime(19289): 	at java.lang.reflect.Method.invoke(Native Method)
[        ] E/AndroidRuntime(19289): 	at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:548)
[        ] E/AndroidRuntime(19289): 	at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:936)
[        ] E/AndroidRuntime(19289): Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'int android.media.EncoderProfiles$VideoProfile.getWidth()' on a null object reference
[        ] E/AndroidRuntime(19289): 	at io.flutter.plugins.camera.features.resolution.ResolutionFeature.configureResolution(ResolutionFeature.java:244)
[        ] E/AndroidRuntime(19289): 	at io.flutter.plugins.camera.features.resolution.ResolutionFeature.<init>(ResolutionFeature.java:50)
[        ] E/AndroidRuntime(19289): 	at io.flutter.plugins.camera.features.CameraFeatureFactoryImpl.createResolutionFeature(CameraFeatureFactoryImpl.java:58)
[        ] E/AndroidRuntime(19289): 	at io.flutter.plugins.camera.features.CameraFeatures.init(CameraFeatures.java:71)
[        ] E/AndroidRuntime(19289): 	at io.flutter.plugins.camera.Camera.<init>(Camera.java:217)
[        ] E/AndroidRuntime(19289): 	at io.flutter.plugins.camera.MethodCallHandlerImpl.instantiateCamera(MethodCallHandlerImpl.java:386)
[        ] E/AndroidRuntime(19289): 	at io.flutter.plugins.camera.MethodCallHandlerImpl.lambda$onMethodCall$0$io-flutter-plugins-camera-MethodCallHandlerImpl(MethodCallHandlerImpl.java:81)
[        ] E/AndroidRuntime(19289): 	at io.flutter.plugins.camera.MethodCallHandlerImpl$$ExternalSyntheticLambda0.onResult(Unknown Source:6)
[        ] E/AndroidRuntime(19289): 	at io.flutter.plugins.camera.CameraPermissions.lambda$requestPermissions$0$io-flutter-plugins-camera-CameraPermissions(CameraPermissions.java:58)
[        ] E/AndroidRuntime(19289): 	at io.flutter.plugins.camera.CameraPermissions$$ExternalSyntheticLambda0.onResult(Unknown Source:4)
[        ] E/AndroidRuntime(19289): 	at io.flutter.plugins.camera.CameraPermissions$CameraRequestPermissionsListener.onRequestPermissionsResult(CameraPermissions.java:113)
[        ] E/AndroidRuntime(19289): 	at io.flutter.embedding.engine.FlutterEngineConnectionRegistry$FlutterEngineActivityPluginBinding.onRequestPermissionsResult(FlutterEngineConnectionRegistry.java:779)
[        ] E/AndroidRuntime(19289): 	at io.flutter.embedding.engine.FlutterEngineConnectionRegistry.onRequestPermissionsResult(FlutterEngineConnectionRegistry.java:411)
[        ] E/AndroidRuntime(19289): 	at io.flutter.embedding.android.FlutterActivityAndFragmentDelegate.onRequestPermissionsResult(FlutterActivityAndFragmentDelegate.java:761)
[        ] E/AndroidRuntime(19289): 	at io.flutter.embedding.android.FlutterActivity.onRequestPermissionsResult(FlutterActivity.java:743)
[        ] E/AndroidRuntime(19289): 	at android.app.Activity.dispatchRequestPermissionsResult(Activity.java:8759)
[        ] E/AndroidRuntime(19289): 	at android.app.Activity.dispatchActivityResult(Activity.java:8617)
[        ] E/AndroidRuntime(19289): 	at android.app.ActivityThread.deliverResults(ActivityThread.java:5340)
[        ] E/AndroidRuntime(19289): 	... 13 more
[ +100 ms] I/Process (19289): Sending signal. PID: 19289 SIG: 9
[  +60 ms] Service protocol connection closed.
[        ] Lost connection to device.
[   +1 ms] DevFS: Deleting filesystem on the device (file:///data/user/0/com.example.issue_109769/code_cache/issue_109769RSNUON/issue_109769/)
[  +18 ms] executing: C:\android-sdk\platform-tools\adb.exe -s emulator-5554 shell am force-stop com.example.issue_109769
Code Sample (from official example)
// 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({Key? key}) : super(key: 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;
    default:
      throw ArgumentError('Unknown lens direction');
  }
}

void _logError(String code, String? message) {
  if (message != null) {
    print('Error: $code\nError Message: $message');
  } else {
    print('Error: $code');
  }
}

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();
    _ambiguate(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() {
    _ambiguate(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) {
      onNewCameraSelected(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) {
      if (description == null) {
        return;
      }

      onNewCameraSelected(description);
    }

    if (_cameras.isEmpty) {
      _ambiguate(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:
                  controller != null && controller!.value.isRecordingVideo
                      ? null
                      : 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 {
    final CameraController? oldController = controller;
    if (oldController != null) {
      // `controller` needs to be set to null before getting disposed,
      // to avoid a race condition when we use the controller that is being
      // disposed. This happens when camera permission dialog shows up,
      // which triggers `didChangeAppLifecycleState`, which disposes and
      // re-creates the controller.
      controller = null;
      await oldController.dispose();
    }

    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) {
      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({Key? key}) : super(key: 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());
}

/// This allows a value of type T or T? to be treated as a value of type T?.
///
/// We use this so that APIs that have become non-nullable can still be used
/// with `!` and `?` on the stable branch.
// TODO(ianh): Remove this once we roll stable in late 2021.
T? _ambiguate<T>(T? value) => value;
flutter doctor -v
[✓] Flutter (Channel master, 3.1.0-0.0.pre.2403, on Microsoft Windows [Version 10.0.22000.856], locale en-IN)
    • Flutter version 3.1.0-0.0.pre.2403 on channel master at C:\Users\Nabeel Parkar\fvm\versions\master
    • Upstream repository https://github.com/flutter/flutter.git
    • Framework revision a10c921aba (3 hours ago), 2022-08-21 23:44:38 -0400
    • Engine revision d311584c79
    • Dart version 2.19.0 (build 2.19.0-120.0.dev)
    • DevTools version 2.16.0

[✓] Android toolchain - develop for Android devices (Android SDK version 33.0.0)
    • Android SDK at C:\android-sdk
    • Platform android-33, build-tools 33.0.0
    • Java binary at: C:\Program Files\Android\Android Studio\jre\bin\java
    • Java version OpenJDK Runtime Environment (build 11.0.12+7-b1504.28-7817840)
    • All Android licenses accepted.

[✓] Chrome - develop for the web
    • CHROME_EXECUTABLE = C:\Program Files\BraveSoftware\Brave-Browser\Application\brave.exe

[✓] Visual Studio - develop for Windows (Visual Studio Community 2022 17.2.6)
    • Visual Studio at C:\Program Files\Microsoft Visual Studio\2022\Community
    • Visual Studio Community 2022 version 17.2.32630.192
    • Windows 10 SDK version 10.0.19041.0

[✓] Android Studio (version 2021.2)
    • Android Studio at C:\Program Files\Android\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.12+7-b1504.28-7817840)

[✓] IntelliJ IDEA Ultimate Edition (version 2022.2)
    • IntelliJ at C:\Program Files\JetBrains\IntelliJ IDEA 2022.2
    • Flutter plugin version 69.0.5
    • Dart plugin version 222.3739.24

[✓] VS Code (version 1.70.2)
    • VS Code at C:\Users\Nabeel Parkar\AppData\Local\Programs\Microsoft VS Code
    • Flutter extension version 3.46.0

[✓] Connected device (3 available)
    • Windows (desktop) • windows • windows-x64    • Microsoft Windows [Version 10.0.22000.856]
    • Chrome (web)      • chrome  • web-javascript • unknown
    • Edge (web)        • edge    • web-javascript • Microsoft Edge 104.0.1293.54

[✓] HTTP Host Availability
    • All required HTTP hosts are available

• No issues found!

@exaby73 exaby73 added c: crash Stack traces logged to the console platform-android Android applications specifically plugin p: camera The camera plugin has reproducible steps The issue has been confirmed reproducible and is ready to work on c: fatal crash Crashes that terminate the process found in release: 3.1 Found to occur in 3.1 and removed in triage Presently being triaged by the triage team labels Aug 19, 2022
@darshankawar darshankawar added p: first party e: OS-version specific Affects only some versions of the relevant operating system labels Aug 22, 2022
@stuartmorgan stuartmorgan added the P1 High-priority issues at the top of the work list label Aug 25, 2022
@acoutts
Copy link

acoutts commented Aug 26, 2022

Investigating a bit -

List<EncoderProfiles.VideoProfile> videoProfiles = recordingProfile.getVideoProfiles();

This is returning an empty list as [null] instead of the profiles to use.

I did a test and if I comment out and use the "deprecated" code for determining the resolution, the camera works again
Screen Shot 2022-08-26 at 5 14 06 PM

Looks like the change for this was introduced because CamcorderProfile was deprecated in API 31:
flutter/plugins#4423

@shliama what device have you confirmed the issue on? For me, I can reproduce the issue on my Pixel 5 after upgrading it to android 13 today.

Could this be a bug in android 13? From the docs:

Screen Shot 2022-08-26 at 5 50 36 PM

But when I try to print the result of getAll, it's always a null list:
Screen Shot 2022-08-26 at 5 54 08 PM

2022-08-26 17:53:54.979 18139-18139/io.flutter.plugins.cameraexample D/Camera: Test QUALITY_LOW:  | [null]hasLow: true
2022-08-26 17:53:54.980 18139-18139/io.flutter.plugins.cameraexample D/Camera: Test QUALITY_HIGH:  | [null]hasHigh: true

@shliama
Copy link
Author

shliama commented Sep 2, 2022

@acoutts I reproduced it on my Pixel 4a 5G but also on AVD with emulated camera. So I'm pretty sure it's not a device specific but Android 13 issue.

@icarusoft
Copy link

I have the same problem on my Pixel 6 Pro after I upgraded to Android 13, worked fine before. Glad you are working on this, it is blocking me right now :)

@asafbennatan
Copy link

same issue with my pixel 6

@acoutts
Copy link

acoutts commented Sep 2, 2022

Please try my quick fix here:

  camera_android:
    git:
      url: https://github.com/bottlepay/plugins.git
      path: packages/camera/camera_android
      ref: e1a4dba770da9bc3cf9f858bac6837083f8b9059

I just commented out the "new" method so it's using the deprecated one. It does make the camera work again but I'm not sure how the permanent fix should work. Hopefully someone with more knowledge of the camera api can chime in.

@asafbennatan
Copy link

@acoutts thanks , should i add this along side regular camera dependency ? (pub get complains about dependency mismatch) , or should i do :

  camera:
    git:
      url: https://github.com/bottlepay/plugins.git
      path: packages/camera/camera
      ref: e1a4dba770da9bc3cf9f858bac6837083f8b9059

@acoutts
Copy link

acoutts commented Sep 2, 2022

The easiest way is to just add it under dependency_overrides and leave your other one there.

https://dart.dev/tools/pub/dependencies#dependency-overrides

@asafbennatan
Copy link

yes , just did that , it works ,
thanks alot !

@asafbennatan
Copy link

@acoutts should this work for older android versions ?

@asafbennatan
Copy link

seems that it doesnt work for android 12

@acoutts
Copy link

acoutts commented Sep 2, 2022

I just tested it on a pixel 6 android 12 and it works for me..

@asafbennatan
Copy link

Tested it on pixel 3 with android 12 , will reverify again tomorrow, thanks!

@asafbennatan
Copy link

@acoutts you are right , didnt work due to a different issue

@rivella50
Copy link

@elmar001 Thank you. But i meant the version(s) of the camera package itself. Your fix is from October 10, this means version 0.10.0+3. But what about e.g. the current version 0.10.3?

@elmar001
Copy link

elmar001 commented Feb 1, 2023

@elmar001 Thank you. But i meant the version(s) of the camera package itself. Your fix is from October 10, this means version 0.10.0+3. But what about e.g. the current version 0.10.3?
I have not updated to the newer version of that package yet. Still using old one as it works without any issue. Not sure about newer version you are mentioning.

@hirensamtani
Copy link

The issue is still not resolved in 0.10.3.
Simply try running the example code of this plugin with compileSDK 33. The steps are reproduced.
Patching it by compiling through SDK 31 is not an adequate solution as many plugins now require SDK 33.
Request to escalate this issue to priority.

@faisalmushtaq007

This comment was marked as off-topic.

@zq0flaz

This comment was marked as off-topic.

@auto-submit auto-submit bot closed this as completed Feb 3, 2023
@faisalmushtaq007
Copy link

why is this issue closed???

@lohnn
Copy link

lohnn commented Feb 6, 2023

Looks like it is fixed with the workaround from this:
flutter/plugins#7073
However it seems like it is not released to pub.dev yet.

@PerLycke
Copy link

PerLycke commented Feb 6, 2023 via email

@faisalmushtaq007
Copy link

@PerLycke why havent they updated https://pub.dev/packages/camera package

@PerLycke
Copy link

PerLycke commented Feb 6, 2023

@PerLycke why havent they updated https://pub.dev/packages/camera package

Because it's not needed. It's a transitive dependency which got an incremental update and will be updated if you run the upgrade command.

@mauriziopinotti
Copy link

I confirm upgrading camera_android to 0.10.4 works even after reverting targetSdkVersion to 33 👍

@baek-b
Copy link

baek-b commented Feb 6, 2023

I confirm upgrading camera_android to 0.10.4 works even after reverting targetSdkVersion to 33 👍

What's your minSDK version?

@mauriziopinotti
Copy link

I confirm upgrading camera_android to 0.10.4 works even after reverting targetSdkVersion to 33 +1

What's your minSDK version?

21 but it shouldn't be relevant.

@Origogi
Copy link

Origogi commented Feb 6, 2023

@mauriziopinotti when 0.10.4 release??

@mauriziopinotti
Copy link

@mauriziopinotti when 0.10.4 release??

Version 0.10.4 of camera_android has been released (not to be confused with camera).

@oguzhankosar
Copy link

Why is this issue closed? The camera plugin still doesn't work, I don't want to use camera_android.

@dmytrohurskyi
Copy link

Why is this issue closed? The camera plugin still doesn't work, I don't want to use camera_android.

You don't need to use camera_android explicitly, it's already used by camera package, because it's a transitive dependency. All you need to do is to run flutter pub upgrade and it will automatically update dependencies, including camera_android. And then you will see that this issue has been fixed.

nickmeinhold added a commit to enspyrco/monorepo that referenced this issue Feb 8, 2023
The bug will be fixed in an upcoming build

see: flutter/flutter#109769
enspyr-admin pushed a commit to enspyrco/monorepo that referenced this issue Feb 8, 2023
* Added the movenet tflite model

* Added Keypoint model to hold output data

* Added logic for interpreting images & viewing results

- a callback passed to `startImageStream` in CameraView that converts
the pixel data from the camera into a format the TFLite plugin can use.
- KeypointViewer, a CustomPaint that paints circles for each keypoint.
- a ValueNotifier to tie the two together.

* Added a profile launch config

* Added workaround for Android 13 bug

The bug will be fixed in an upcoming build

see: flutter/flutter#109769

* Commit automatic changes made by running a build

* Encapsulate inference & model loading in classes

I made a separat class for extracting the model from the asset bundle,
saving locally and holding on to the file path.

I moved the code for running inference to a separate class. The code is
now in InferenceRunner. For now this is using the Interpreter just as
the CameraView was but in the next step the interpreter will be created
in an Isolate and the runner will send and recieve message with the
Isolate.

I also added an extension on CameraImage that converts the image data to
the form that the input tensor needs. The extension is just for
readability.

We now combine the model loading and inference setup in the MainScreen
then the CameraView asks the InferenceRunner to run inference on each
image that the image stream receives.

* Move views into separate folder for findability

* Add isolate based implementation of InferenceRunner

Co-authored-by: Trevor Davis <tzendou@gmail.com>

---------

Co-authored-by: Trevor Davis <tzendou@gmail.com>
@hsandyque
Copy link

hsandyque commented Feb 10, 2023

Why is this issue closed? The camera plugin still doesn't work, I don't want to use camera_android.

You don't need to use camera_android explicitly, it's already used by camera package, because it's a transitive dependency. All you need to do is to run flutter pub upgrade and it will automatically update dependencies, including camera_android. And then you will see that this issue has been fixed.

@dmytrohurskyi
I get this issue when building apk for test, it still reference to camera_android 0.10.3 folder (there are 2 folders 0.10.3 and 0.10.4 on pub_cache), how to fix it?

@rivella50
Copy link

You could try

dependency_overrides:
  camera_android: 0.10.4

@hsandyque
Copy link

You could try

dependency_overrides:
  camera_android: 0.10.4

Not working,I don't know if it only works on application instead of plugin, I've try to clean and rebuild, but still not working, should I file a new issue for tracking?

@mauriziopinotti
Copy link

You could try

dependency_overrides:
  camera_android: 0.10.4

Not working,I don't know if it only works on application instead of plugin, I've try to clean and rebuild, but still not working, should I file a new issue for tracking?

Just do a pub upgrade, camera_android is a transitive dependency. After upgrading your pubspec.lock should look like this:

  camera_android:
    dependency: transitive
    description:
      name: camera_android
      sha256: e491c836147f60dd8a54cf3895fd2960e13b21b78a9d15b563a1b6c70894f142
      url: "https://pub.dev"
    source: hosted
    version: "0.10.4"

@hsandyque
Copy link

You could try

dependency_overrides:
  camera_android: 0.10.4

Not working,I don't know if it only works on application instead of plugin, I've try to clean and rebuild, but still not working, should I file a new issue for tracking?

Just do a pub upgrade, camera_android is a transitive dependency. After upgrading your pubspec.lock should look like this:

  camera_android:
    dependency: transitive
    description:
      name: camera_android
      sha256: e491c836147f60dd8a54cf3895fd2960e13b21b78a9d15b563a1b6c70894f142
      url: "https://pub.dev"
    source: hosted
    version: "0.10.4"

My pubspec.lock

camera_android:
dependency: "direct overridden"
description:
name: camera_android
sha256: e491c836147f60dd8a54cf3895fd2960e13b21b78a9d15b563a1b6c70894f142
url: "https://pub.dev"
source: hosted
version: "0.10.4"

@github-actions
Copy link

github-actions bot commented Mar 3, 2023

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.

@github-actions github-actions bot locked as resolved and limited conversation to collaborators Mar 3, 2023
@flutter-triage-bot flutter-triage-bot bot added the package flutter/packages repository. See also p: labels. label Jul 5, 2023
auto-submit bot pushed a commit to flutter/packages that referenced this issue Aug 21, 2023
…ower than 12 (#4635)

The the solution of the issue flutter/flutter#109769 in the #7073 causes a crashes when the Android SDK version is lower than 31, due to EncoderProfiles not being found on these devices. This issue was solved putting the EncoderProfiles declaration after the check for SDK version.

based on flutter/plugins#7073 by @camsim99.

Fixes flutter/flutter#109769 in Android lower than 12.
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
c: crash Stack traces logged to the console c: fatal crash Crashes that terminate the process customer: crowd Affects or could affect many people, though not necessarily a specific customer. e: OS-version specific Affects only some versions of the relevant operating system found in release: 3.1 Found to occur in 3.1 has reproducible steps The issue has been confirmed reproducible and is ready to work on p: camera The camera plugin P1 High-priority issues at the top of the work list package flutter/packages repository. See also p: labels. platform-android Android applications specifically
Projects
None yet