Repository navigation
Closed
Labels
P1High-priority issues at the top of the work listHigh-priority issues at the top of the work listfound in release: 3.44Found to occur in 3.44Found to occur in 3.44p: cameraThe camera pluginThe camera pluginpackageflutter/packages repository. See also p: labels.flutter/packages repository. See also p: labels.platform-androidAndroid applications specificallyAndroid applications specificallyteam-androidOwned by Android platform teamOwned by Android platform teamtriaged-androidTriaged by Android platform teamTriaged by Android platform team
Description
What package does this bug report belong to?
camera
What target platforms are you seeing this bug on?
Android
Have you already upgraded your packages?
Yes
Dependency versions
pubspec.lock
packages:
camera:
dependency: "direct main"
description:
name: camera
sha256: "558230d6ce6ccea856b32d390db7e7b557adf4d9320aa614481bd3f2f608953f"
url: "https://pub.dev"
source: hosted
version: "0.12.0+2"
camera_android_camerax:
dependency: transitive
description:
name: camera_android_camerax
sha256: "30f34108480912ac444c7d3c942005abb8f42baf730bf6f81cedfbfa035b2c21"
url: "https://pub.dev"
source: hosted
version: "0.7.4+3"
Steps to reproduce
Steps to reproduce
- Add camera: 0.12.0+2 (or any version pulling camera_android_camerax with transitive camera-core:1.6.1) to pubspec.yaml.
- Run flutter pub get.
- Run flutter run or flutter build apk.
- Compilation fails during the :camera_android_camerax:compileDebugJavaWithJavac Gradle task.
Expected results
The Android project should build and compile successfully without missing transitive annotation/type dependencies.
Actual results
The Java compiler fails with an error stating that androidx.concurrent.futures.CallbackToFutureAdapter cannot be found while processing @org.jspecify.annotations.NonNull on SurfaceRequest.mSurfaceRecreationCompleter.
Code sample
Code sample
// Copyright 2013 The Flutter Authors
// 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 final AnimationController _flashModeControlRowAnimationController;
late final CurvedAnimation _flashModeControlRowAnimation;
late final AnimationController _exposureModeControlRowAnimationController;
late final CurvedAnimation _exposureModeControlRowAnimation;
late final AnimationController _focusModeControlRowAnimationController;
late final CurvedAnimation _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();
_flashModeControlRowAnimation.dispose();
_exposureModeControlRowAnimationController.dispose();
_exposureModeControlRowAnimation.dispose();
_focusModeControlRowAnimationController.dispose();
_focusModeControlRowAnimation.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() {
return Row(
mainAxisSize: MainAxisSize.min,
children: <Widget>[
if (videoController case final VideoPlayerController controller?)
Container(
width: 64.0,
height: 64.0,
decoration: BoxDecoration(border: Border.all(color: Colors.pink)),
child: Center(
child: AspectRatio(
aspectRatio: controller.value.aspectRatio,
child: VideoPlayer(controller),
),
),
)
else if (imageFile?.path case final String path)
Container(
width: 64.0,
height: 64.0,
decoration: BoxDecoration(border: Border.all(color: Colors.pink)),
// 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.
child: kIsWeb ? Image.network(path) : Image.file(File(path)),
),
],
);
}
/// 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(
foregroundColor: controller?.value.exposureMode == ExposureMode.auto
? Colors.orange
: Colors.blue,
);
final ButtonStyle styleLocked = TextButton.styleFrom(
foregroundColor: controller?.value.exposureMode == ExposureMode.locked
? Colors.orange
: Colors.blue,
);
return SizeTransition(
sizeFactor: _exposureModeControlRowAnimation,
child: ClipRect(
child: ColoredBox(
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(
foregroundColor: controller?.value.focusMode == FocusMode.auto ? Colors.orange : Colors.blue,
);
final ButtonStyle styleLocked = TextButton.styleFrom(
foregroundColor: controller?.value.focusMode == FocusMode.locked
? Colors.orange
: Colors.blue,
);
return SizeTransition(
sizeFactor: _focusModeControlRowAnimation,
child: ClipRect(
child: ColoredBox(
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 toggles = <Widget>[];
void onChanged(CameraDescription? description) {
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)),
value: cameraDescription,
),
),
);
}
}
return Expanded(
child: SizedBox(
height: 56.0,
child: RadioGroup<CameraDescription>(
groupValue: controller?.description,
onChanged: onChanged,
child: ListView(scrollDirection: Axis.horizontal, 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(
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(
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.');
case 'CameraAccessDeniedWithoutPrompt':
// iOS only
showInSnackBar('Please go to Settings app to enable camera access.');
case 'CameraAccessRestricted':
// iOS only
showInSnackBar('Camera access is restricted.');
case 'AudioAccessDenied':
showInSnackBar('You have denied audio access.');
case 'AudioAccessDeniedWithoutPrompt':
// iOS only
showInSnackBar('Please go to Settings app to enable audio access.');
case 'AudioAccessRestricted':
// iOS only
showInSnackBar('Audio access is restricted.');
default:
_showCameraException(e);
}
}
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 await 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 vController = kIsWeb
? VideoPlayerController.networkUrl(Uri.parse(videoFile!.path))
: VideoPlayerController.file(File(videoFile!.path));
videoPlayerListener = () {
if (videoController != 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());
}
}
/// Getting available cameras for testing.
@visibleForTesting
List<CameraDescription> get cameras => _cameras;
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());
}Screenshots or Videos
Screenshots / Video demonstration
N/A (Build time error)
Logs
Logs
Execution failed for task ':camera_android_camerax:compileDebugJavaWithJavac'.
> Compilation failed; see the compiler output below.
/Users/.../.gradle/caches/9.1.0/transforms/022a8c9341fe74a15be652672c7b27a8/transformed/camera-core-1.6.1-api.jar(/androidx/camera/core/SurfaceRequest.class): error: Cannot attach type annotations @org.jspecify.annotations.NonNull to SurfaceRequest.mSurfaceRecreationCompleter:
class file for androidx.concurrent.futures.CallbackToFutureAdapter not found
1 error
* Try:
> Check your code and dependencies to fix the compilation error(s)
> Run with --scan to generate a Build Scan.
BUILD FAILED in 3s
Error: Gradle task assembleDebug failed with exit code 1Flutter Doctor output
Doctor output
[✓] Flutter (Channel stable, 3.44.8, on macOS 26.6 25G72 darwin-arm64, locale en-IN) [1,084ms]
• Flutter version 3.44.8 on channel stable at /Users/DIGVIJAYSINH/fvm/versions/stable
• Upstream repository https://github.com/flutter/flutter.git
• Framework revision 058e0af2c2 (11 days ago), 2026-07-23 10:56:21 -0700
• Engine revision 0cd610717b
• Dart version 3.12.2
• DevTools version 2.57.0
• Feature flags: enable-web, no-enable-linux-desktop, no-enable-macos-desktop, no-enable-windows-desktop, enable-android, enable-ios, cli-animations, enable-native-assets, enable-swift-package-manager, omit-legacy-version-file, enable-lldb-debugging, enable-uiscene-migration
[✓] Android toolchain - develop for Android devices (Android SDK version 37.0.0) [6.8s]
• Android SDK at /Users/DIGVIJAYSINH/Library/Android/sdk
• Emulator version 37.1.11.0 (build_id 15917651) (CL:N/A)
• Platform android-37.0, build-tools 37.0.0
• Java binary at: /Applications/Android Studio.app/Contents/jbr/Contents/Home/bin/java
This is the JDK bundled with the latest Android Studio installation on this machine.
To manually set the JDK path, use: `flutter config --jdk-dir="path/to/jdk"`.
• Java version OpenJDK Runtime Environment (build 25.0.2+-15348964-b329.117)
• All Android licenses accepted.
[✓] Xcode - develop for iOS and macOS (Xcode 26.6) [1,910ms]
• Xcode at /Applications/Xcode.app/Contents/Developer
• Build 17F113
• CocoaPods version 1.17.0
[✓] Chrome - develop for the web [3ms]
• Chrome at /Applications/Google Chrome.app/Contents/MacOS/Google Chrome
[✓] Connected device (4 available) [6.2s]
• SM M366B (mobile) • RZGL52CEGDA • android-arm64 • Android 16 (API 36)
• SM M366B (wireless) (mobile) • adb-RZGL52CEGDA-xFo8D2._adb-tls-connect._tcp • android-arm64 • Android 16 (API 36)
• iPhone 17 Pro Max (mobile) • 7F0D4A51-114F-4CFC-B76B-7E5206591518 • ios • com.apple.CoreSimulator.SimRuntime.iOS-26-5 (simulator)
• Chrome (web) • chrome • web-javascript • Google Chrome 151.0.7922.72
[✓] Network resources [448ms]
• All expected network resources are available.
• No issues found!Reacted by Tim Moritz Kühle and Damiano Ferrari
Metadata
Metadata
Assignees
Labels
P1High-priority issues at the top of the work listHigh-priority issues at the top of the work listfound in release: 3.44Found to occur in 3.44Found to occur in 3.44p: cameraThe camera pluginThe camera pluginpackageflutter/packages repository. See also p: labels.flutter/packages repository. See also p: labels.platform-androidAndroid applications specificallyAndroid applications specificallyteam-androidOwned by Android platform teamOwned by Android platform teamtriaged-androidTriaged by Android platform teamTriaged by Android platform team
Activity
saurabh-mirajkar commentedon Aug 4, 2026
Closing as a duplicate of #177972. This type of issue is better suited for community support channels like StackOverflow. Thank you!
digvijaysinh-cloudemy commentedon Aug 4, 2026
@saurabh-mirajkar check this PR also work for me this is a issue from a Plugin
saurabh-mirajkar commentedon Aug 4, 2026
Thanks for the update. I also tested this using the shared code sample on the latest stable version (3.44.8) but wasn't able to reproduce the reported build failure. I also saw the linked PR. While it may address a specific dependency resolution scenario, I wasn't able to reproduce the issue locally based on the information provided. Since the existing duplicate (#177972) is already closed, we'll keep this issue closed. If you're able to provide a minimal reproducible example that consistently reproduces the problem on the latest stable release, please file a new issue with the complete reproduction steps and
flutter doctor -voutput. Thank you.dhc-tech commentedon Aug 5, 2026
Reopening request — I have a clean, minimal, 100% reproducible repro on the latest stable channel with zero project customization:
Fails every time with:
Root cause (verified via
androidx.camera:camera-core:1.6.1's own Gradle module metadata):camera-coredeclaresandroidx.concurrent:concurrent-futuresonly on its runtime variant, not its api/compile variant. But its compiledSurfaceRequest.classcarries a compile-time jspecify@NonNulltype annotation referencingCallbackToFutureAdapter, which javac needs on the compile classpath to fully process — even though no camera_android_camerax source calls it directly. Since the defaultflutter createtemplate pins AGP 9.0.1 (as of Flutter 3.44.8 stable), this classpath gap is exposed duringcompileDebugJavaWithJavac.flutter doctor -v:Toolchain versions in play:
flutter createon stable 3.44.8,android/settings.gradle.kts)I suspect the earlier "unable to reproduce" was on an older Flutter/AGP combination, since this default-template repro fails 100% of the time on current stable. Happy to provide the full project zip or a screen recording if useful. PR with fix + regression test: flutter/packages#12359
dhc-tech commentedon Aug 5, 2026
Minimal repro repo (exact steps + README with root cause): https://github.com/dhc-tech/camera-android-camerax-build-repro
saurabh-mirajkar commentedon Aug 5, 2026
@dhc-tech Thanks for providing the additional details.
I was able to reproduce this issue on the latest stable Flutter release (3.44.8) after upgrading to Android Studio Quail (2026.1.3) and following the reproduction instructions you shared.
Since this is reproducible on a fresh project with the latest stable, I'm reopening the issue for further investigation.
8 remaining items
camsim99 commentedon Aug 12, 2026
Looks like an upstream fix is in progress: https://b.corp.google.com/issues/543937345. Still think landing flutter/packages#12373 is a good idea until we can update our dependencies to fix the issue, though.
camsim99 commentedon Aug 19, 2026
Re-opening to track updating our dependencies and removing the workaround added in flutter/packages#12373
[camera_android_camerax] Add explicit concurrent-futures dependency (f…
[camera_android_camerax] Bump cameraxVersion to 1.6.2, remove concurr…
[camera_android_camerax] Bump cameraxVersion to 1.6.2, remove concurr…
github-actions commentedon Sep 23, 2026
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 -vand a minimal reproduction of the issue.