### Example pubspec.yaml Dependency Source: https://pub.dev/packages/camera_android_camerax/install This is an example of how the camera_android_camerax dependency will appear in your pubspec.yaml file after running the add command. ```yaml dependencies: camera_android_camerax: ^0.7.2+1 ``` -------------------------------- ### Example App Main Dart File Source: https://pub.dev/packages/camera_web/example This is the main entry point for the example application. It sets up a basic Flutter app that displays text and logs results to the console. ```dart // 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 'package:flutter/material.dart'; void main() => runApp(const MyApp()); /// App for testing class MyApp extends StatelessWidget { /// Default Constructor const MyApp({super.key}); @override Widget build(BuildContext context) { return const Directionality( textDirection: TextDirection.ltr, child: Text('Testing... Look at the console output for results!'), ); } } ``` -------------------------------- ### Start Video Recording Implementation Source: https://pub.dev/packages/camera/example Internal method to start video recording. Ensures the camera is initialized and not already recording. Handles CameraExceptions. ```Dart Future 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) { _showCameraCameraException(e); return; } } ``` -------------------------------- ### Start Video Recording Logic Source: https://pub.dev/packages/camera_avfoundation/example Contains the core logic for starting video recording. It checks for camera initialization and ensures no recording is already active. ```dart Future 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; } } ``` -------------------------------- ### Camera Example Home Widget Source: https://pub.dev/packages/camera_avfoundation/example The main widget for the camera example application. It sets up the scaffold, app bar, and the main column layout for camera controls and preview. ```dart // 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 'dart:math'; import 'package:camera_platform_interface/camera_platform_interface.dart'; import 'package:flutter/foundation.dart'; import 'package:flutter/material.dart'; import 'package:flutter/scheduler.dart'; import 'package:video_player/video_player.dart'; import 'camera_controller.dart'; import 'camera_preview.dart'; /// Camera example home widget. class CameraExampleHome extends StatefulWidget { /// Default Constructor const CameraExampleHome({super.key}); @override State 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 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 _flashModeControlRowAnimation; late AnimationController _exposureModeControlRowAnimationController; late Animation _exposureModeControlRowAnimation; late AnimationController _focusModeControlRowAnimationController; late Animation _focusModeControlRowAnimation; double _minAvailableZoom = 1.0; double _maxAvailableZoom = 1.0; double _currentScale = 1.0; double _baseScale = 1.0; // Counting pointers (number of user fingers on screen) int _pointers = 0; @override void initState() { super.initState(); WidgetsBinding.instance.addObserver(this); _flashModeControlRowAnimationController = AnimationController( duration: const Duration(milliseconds: 300), vsync: this, ); _flashModeControlRowAnimation = CurvedAnimation( parent: _flashModeControlRowAnimationController, curve: Curves.easeInCubic, ); _exposureModeControlRowAnimationController = AnimationController( duration: const Duration(milliseconds: 300), vsync: this, ); _exposureModeControlRowAnimation = CurvedAnimation( parent: _exposureModeControlRowAnimationController, curve: Curves.easeInCubic, ); _focusModeControlRowAnimationController = AnimationController( duration: const Duration(milliseconds: 300), vsync: this, ); _focusModeControlRowAnimation = CurvedAnimation( parent: _focusModeControlRowAnimationController, curve: Curves.easeInCubic, ); } @override void dispose() { WidgetsBinding.instance.removeObserver(this); _flashModeControlRowAnimationController.dispose(); _exposureModeControlRowAnimationController.dispose(); super.dispose(); } @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); } } @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar(title: const Text('Camera example')), body: Column( children: [ 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( ``` -------------------------------- ### Full Screen Camera Preview Source: https://pub.dev/packages/camera This example demonstrates how to display a full-screen camera preview using the Flutter camera plugin. It initializes the camera, handles potential access errors, and disposes of the controller when done. ```dart import 'package:camera/camera.dart'; import 'package:flutter/material.dart'; late List _cameras; Future main() async { WidgetsFlutterBinding.ensureInitialized(); _cameras = await availableCameras(); runApp(const CameraApp()); } /// CameraApp is the Main Application. class CameraApp extends StatefulWidget { /// Default Constructor const CameraApp({super.key}); @override State createState() => _CameraAppState(); } class _CameraAppState extends State { late CameraController controller; @override void initState() { super.initState(); controller = CameraController(_cameras[0], ResolutionPreset.max); controller .initialize() .then((_) { if (!mounted) { return; } setState(() {}); }) .catchError((Object e) { if (e is CameraException) { switch (e.code) { case 'CameraAccessDenied': // Handle access errors here. break; default: // Handle other errors here. break; } } }); } @override void dispose() { controller.dispose(); super.dispose(); } @override Widget build(BuildContext context) { if (!controller.value.isInitialized) { return Container(); } return MaterialApp(home: CameraPreview(controller)); } } ``` -------------------------------- ### Add camera_platform_interface to pubspec.yaml Source: https://pub.dev/packages/camera_platform_interface/install This is an example of how the camera_platform_interface dependency will appear in your pubspec.yaml file after running the add command. ```yaml dependencies: camera_platform_interface: ^2.13.0 ``` -------------------------------- ### Start Video Player Source: https://pub.dev/packages/camera_android_camerax/example Initializes and plays a video from a file or network URL. This is used to display recorded videos within the app. ```dart Future _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(); } ``` -------------------------------- ### Start Video Player Source: https://pub.dev/packages/camera_avfoundation/example Initializes and plays a video file using the VideoPlayerController. Handles web and file-based video sources and updates the UI state. ```dart Future _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(); } ``` -------------------------------- ### Import camera_web in Dart Source: https://pub.dev/packages/camera_web/install Import the camera_web package into your Dart files to start using its functionalities. ```dart import 'package:camera_web/camera_web.dart'; ``` -------------------------------- ### Start Video Recording Source: https://pub.dev/packages/camera_avfoundation/example Initiates video recording. It checks if a camera is selected and initialized, and if a recording is not already in progress. ```dart void onVideoRecordButtonPressed() { startVideoRecording().then((_) { if (mounted) { setState(() {}); } }); } ``` -------------------------------- ### Import camera_platform_interface in Dart Source: https://pub.dev/packages/camera_platform_interface/install Import the camera_platform_interface library into your Dart files to start using its functionalities. ```dart import 'package:camera_platform_interface/camera_platform_interface.dart'; ``` -------------------------------- ### Get Available Cameras Source: https://pub.dev/packages/camera/example Retrieves a list of available camera descriptions on the device. Marked as visible for testing purposes. ```dart /// Getting available cameras for testing. @visibleForTesting List get cameras => _cameras; List _cameras = []; ``` -------------------------------- ### Declare Camera Dependency in pubspec.yaml Source: https://pub.dev/packages/camera/install This is an example of how the camera dependency will appear in your pubspec.yaml file after running `flutter pub add camera`. ```yaml dependencies: camera: ^0.12.0+1 ``` -------------------------------- ### Add camera_android Dependency Source: https://pub.dev/packages/camera_android Use this command to add the camera_android package to your Flutter project. This is required starting from camera version ^0.11.0 to use this plugin instead of camera_android_camerax. ```bash flutter pub add camera_android ``` -------------------------------- ### Handle Video Recording Button Presses Source: https://pub.dev/packages/camera_android_camerax/example Manages the start, stop, pause, and resume actions for video recording based on button presses. Updates UI and shows snackbar messages. ```Dart void onVideoRecordButtonPressed() { startVideoRecording().then((_) { if (mounted) { setState(() {}); } }); } ``` ```Dart void onStopButtonPressed() { stopVideoRecording().then((XFile? file) { if (mounted) { setState(() {}); } if (file != null) { showInSnackBar('Video recorded to ${file.path}'); videoFile = file; _startVideoPlayer(); } }); } ``` ```Dart void onPauseButtonPressed() { pauseVideoRecording().then((_) { if (mounted) { setState(() {}); } showInSnackBar('Video recording paused'); }); } ``` ```Dart void onResumeButtonPressed() { resumeVideoRecording().then((_) { if (mounted) { setState(() {}); } showInSnackBar('Video recording resumed'); }); } ``` -------------------------------- ### Main Function - Initialize Cameras Source: https://pub.dev/packages/camera_android_camerax/example The entry point of the application. It ensures Flutter is initialized, fetches available cameras, and runs the main app widget. ```dart Future 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()); } ``` -------------------------------- ### Initialize CameraController with Media Settings Source: https://pub.dev/packages/camera_android_camerax/example Initializes a CameraController with specified media settings including resolution preset, FPS, video and audio bitrates, and audio enablement. This is useful for setting up the camera with desired recording parameters. ```dart final cameraController = CameraController( cameraDescription, mediaSettings: MediaSettings( resolutionPreset: ResolutionPreset.low, fps: 15, videoBitrate: 200000, audioBitrate: 32000, enableAudio: enableAudio, ), imageFormatGroup: ImageFormatGroup.jpeg, ); ``` -------------------------------- ### Main Function and Camera Initialization Source: https://pub.dev/packages/camera_avfoundation/example Initializes the Flutter binding, fetches available cameras, and runs the CameraApp. Includes error handling for camera retrieval. ```dart Future main() async { // Fetch the available cameras before initializing the app. try { WidgetsFlutterBinding.ensureInitialized(); _cameras = await CameraPlatform.instance.availableCameras(); } on CameraException catch (e) { _logError(e.code, e.description); } runApp(const CameraApp()); } ``` -------------------------------- ### Initialize Camera Controller Source: https://pub.dev/packages/camera_android/example Initializes the camera controller with specified settings. Handles potential camera and audio access exceptions. ```dart Future _initializeCameraController( CameraDescription cameraDescription, ) async { final cameraController = CameraController( cameraDescription, mediaSettings: MediaSettings( resolutionPreset: 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(() {}); } }); try { await cameraController.initialize(); await Future.wait( >[ // The exposure mode is currently not supported on the web. ...!kIsWeb ? >[ CameraPlatform.instance .getMinExposureOffset(cameraController.cameraId) .then( (double value) => _minAvailableExposureOffset = value, ), CameraPlatform.instance .getMaxExposureOffset(cameraController.cameraId) .then( (double value) => _maxAvailableExposureOffset = value, ), ] : >[], CameraPlatform.instance .getMaxZoomLevel(cameraController.cameraId) .then((double value) => _maxAvailableZoom = value), CameraPlatform.instance .getMinZoomLevel(cameraController.cameraId) .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.'); case 'cameraPermission': // Android & web only showInSnackBar('Unknown permission error.'); default: _showCameraException(e); } } if (mounted) { setState(() {}); } } ``` -------------------------------- ### Initialize Camera Controller Source: https://pub.dev/packages/camera_avfoundation/example Initializes a CameraController with specified settings. Handles potential CameraExceptions during initialization and updates UI state. ```dart Future _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(() {}); } }); try { await cameraController.initialize(); await Future.wait( >[ // The exposure mode is currently not supported on the web. ...!kIsWeb ? >[ CameraPlatform.instance .getMinExposureOffset(cameraController.cameraId) .then( (double value) => _minAvailableExposureOffset = value, ), CameraPlatform.instance .getMaxExposureOffset(cameraController.cameraId) .then( (double value) => _maxAvailableExposureOffset = value, ), ] : >[], CameraPlatform.instance .getMaxZoomLevel(cameraController.cameraId) .then((double value) => _maxAvailableZoom = value), CameraPlatform.instance .getMinZoomLevel(cameraController.cameraId) .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.'); case 'cameraPermission': // Android & web only showInSnackBar('Unknown permission error.'); default: _showCameraException(e); } } if (mounted) { setState(() {}); } } ``` -------------------------------- ### Import camera_android_camerax in Dart Source: https://pub.dev/packages/camera_android_camerax/install Import the camera_android_camerax package into your Dart files to start using its functionalities. This import statement is necessary for accessing the package's APIs. ```dart import 'package:camera_android_camerax/camera_android_camerax.dart'; ``` -------------------------------- ### iOS Info.plist Configuration Source: https://pub.dev/packages/camera Add these rows to your Info.plist file to request camera and microphone usage descriptions on iOS. ```xml NSCameraUsageDescription your usage description here NSMicrophoneUsageDescription your usage description here ``` -------------------------------- ### Stop Video Recording Source: https://pub.dev/packages/camera_avfoundation/example Stops the current video recording and returns the recorded file. It updates the UI and shows a snackbar with the file path. If a file is recorded, it starts playing it. ```dart void onStopButtonPressed() { stopVideoRecording().then((XFile? file) { if (mounted) { setState(() {}); } if (file != null) { showInSnackBar('Video recorded to ${file.path}'); videoFile = file; _startVideoPlayer(); } }); } ``` -------------------------------- ### CameraApp Widget Source: https://pub.dev/packages/camera_avfoundation/example The main application widget that sets up the MaterialApp and points to the CameraExampleHome. ```dart class CameraApp extends StatelessWidget { /// Default Constructor const CameraApp({super.key}); @override Widget build(BuildContext context) { return const MaterialApp(home: CameraExampleHome()); } } ``` -------------------------------- ### Initialize Camera Controller and Handle App Lifecycle Source: https://pub.dev/packages/camera_android_camerax/example Initializes the camera controller and manages its lifecycle based on the application's lifecycle states. Disposes the controller when the app is inactive and re-initializes it when the app resumes. ```dart // 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_platform_interface/camera_platform_interface.dart'; import 'package:flutter/foundation.dart'; import 'package:flutter/material.dart'; import 'package:flutter/scheduler.dart'; import 'package:video_player/video_player.dart'; import 'camera_controller.dart'; import 'camera_preview.dart'; /// Camera example home widget. class CameraExampleHome extends StatefulWidget { /// Default Constructor const CameraExampleHome({super.key}); @override State 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 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 _flashModeControlRowAnimation; late AnimationController _exposureModeControlRowAnimationController; late Animation _exposureModeControlRowAnimation; late AnimationController _focusModeControlRowAnimationController; late Animation _focusModeControlRowAnimation; double _minAvailableZoom = 1.0; double _maxAvailableZoom = 1.0; double _currentScale = 1.0; double _baseScale = 1.0; // Counting pointers (number of user fingers on screen) int _pointers = 0; @override void initState() { super.initState(); WidgetsBinding.instance.addObserver(this); _flashModeControlRowAnimationController = AnimationController( duration: const Duration(milliseconds: 300), vsync: this, ); _flashModeControlRowAnimation = CurvedAnimation( parent: _flashModeControlRowAnimationController, curve: Curves.easeInCubic, ); _exposureModeControlRowAnimationController = AnimationController( duration: const Duration(milliseconds: 300), vsync: this, ); _exposureModeControlRowAnimation = CurvedAnimation( parent: _exposureModeControlRowAnimationController, curve: Curves.easeInCubic, ); _focusModeControlRowAnimationController = AnimationController( duration: const Duration(milliseconds: 300), vsync: this, ); _focusModeControlRowAnimation = CurvedAnimation( parent: _focusModeControlRowAnimationController, curve: Curves.easeInCubic, ); } @override void dispose() { WidgetsBinding.instance.removeObserver(this); _flashModeControlRowAnimationController.dispose(); _exposureModeControlRowAnimationController.dispose(); super.dispose(); } // #docregion AppLifecycle @override void didChangeAppLifecycleState(AppLifecycleState state) { final CameraController? cameraController = controller; // App state changed before we got the chance to initialize. if (cameraController == null || !cameraController.value.isInitialized) { return; } if (state == AppLifecycleState.inactive) { cameraController.dispose(); } else if (state == AppLifecycleState.resumed) { _initializeCameraController(cameraController.description); } } // #enddocregion AppLifecycle @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar(title: const Text('Camera example')), body: Column( children: [ Expanded( child: Container( decoration: BoxDecoration( color: Colors.black, border: Border.all( color: controller != null && controller!.value.isRecordingVideo ? Colors.redAccent : Colors.grey, width: 3.0, ), ``` -------------------------------- ### Initialize Camera Controller Source: https://pub.dev/packages/camera/example Initializes the camera controller when the app resumes. Ensures the camera is ready for use after being inactive. ```dart // 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 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 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: [ Expanded( child: Container( decoration: BoxDecoration( color: Colors.black, border: Border.all( color: ``` -------------------------------- ### Handle Camera Exceptions Source: https://pub.dev/packages/camera_android_camerax/example Demonstrates how to catch and handle specific `CameraException` codes, providing user-friendly messages for common issues like camera access denial or restrictions. This ensures a better user experience when camera operations fail. ```dart try { await cameraController.initialize(); await Future.wait(>[ // The exposure mode is currently not supported on the web. ...!kIsWeb ? >[ cameraController.getMinExposureOffset().then( (double value) => _minAvailableExposureOffset = value, ), cameraController.getMaxExposureOffset().then( (double value) => _maxAvailableExposureOffset = value, ), ] : >[], 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); } } ``` -------------------------------- ### Select New Camera Source: https://pub.dev/packages/camera_avfoundation/example Selects a new camera description. If a controller already exists, it updates the description; otherwise, it initializes a new controller for the selected camera. ```dart Future onNewCameraSelected(CameraDescription cameraDescription) async { if (controller != null) { return controller!.setDescription(cameraDescription); } else { return _initializeCameraController(cameraDescription); } } ``` -------------------------------- ### Add camera_web Dependency Source: https://pub.dev/packages/camera_web/install Use this command to add the camera_web package to your Flutter project's dependencies. This command automatically updates your pubspec.yaml file. ```bash $ flutter pub add camera_web ``` -------------------------------- ### Add Camera Dependency to Flutter Project Source: https://pub.dev/packages/camera/install Use this command to add the camera package as a dependency in your Flutter project. This command automatically updates your pubspec.yaml file. ```bash $ flutter pub add camera ``` -------------------------------- ### Add camera_platform_interface Dependency Source: https://pub.dev/packages/camera_platform_interface/install Use this command to add the camera_platform_interface package to your Flutter project's dependencies. ```bash $ flutter pub add camera_platform_interface ``` -------------------------------- ### Take Picture and Handle Result Source: https://pub.dev/packages/camera_android_camerax/example Initiates taking a picture using the camera controller and handles the resulting `XFile`. It updates the UI state with the captured image file and disposes of any active video controller. This is essential for image capture functionality. ```dart void onTakePictureButtonPressed() { takePicture().then((XFile? file) { if (mounted) { setState(() { imageFile = file; videoController?.dispose(); videoController = null; }); if (file != null) { showInSnackBar('Picture saved to ${file.path}'); } } }); } ``` -------------------------------- ### Camera Preview Widget Source: https://pub.dev/packages/camera_avfoundation/example Displays the camera preview or a message if the preview is not ready. Handles tap gestures for focus and pinch gestures for zoom. ```dart 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), ); }, ), ), ); } } ``` -------------------------------- ### Handle Pinch to Zoom Source: https://pub.dev/packages/camera_avfoundation/example Updates the camera zoom level based on pinch gestures. Requires exactly two pointers on the screen. ```dart Future _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 CameraPlatform.instance.setZoomLevel( controller!.cameraId, _currentScale, ); } ``` -------------------------------- ### Import camera_avfoundation in Dart Code Source: https://pub.dev/packages/camera_avfoundation/install Import the camera_avfoundation package into your Dart files to access its functionalities. This is necessary before using any of its classes or methods. ```dart import 'package:camera_avfoundation/camera_avfoundation.dart'; ``` -------------------------------- ### Handle Camera Exception Source: https://pub.dev/packages/camera/example This snippet shows how to catch and display camera-related exceptions. It's useful for providing user feedback on errors. ```dart } on CameraException catch (e) { _showCameraException(e); rethrow; } ``` -------------------------------- ### Pause/Resume Camera Preview Source: https://pub.dev/packages/camera_avfoundation/example Toggles the camera preview between paused and resumed states. It ensures a camera is selected and initialized before attempting to pause or resume. ```dart Future 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(() {}); } } ``` -------------------------------- ### Add camera_android_camerax Dependency Source: https://pub.dev/packages/camera_android_camerax/install Use this command to add the camera_android_camerax package to your Flutter project's dependencies. This command automatically updates your pubspec.yaml file. ```bash $ flutter pub add camera_android_camerax ``` -------------------------------- ### Thumbnail Widget Source: https://pub.dev/packages/camera_avfoundation/example Displays a thumbnail of the captured image or video. Supports both web and non-web platforms. ```dart Widget _thumbnailWidget() { final VideoPlayerController? localVideoController = videoController; return Expanded( child: Align( alignment: Alignment.centerRight, child: Row( mainAxisSize: MainAxisSize.min, children: [ 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.aspectRatio, child: VideoPlayer(localVideoController), ), ), ), ), ], ), ), ); } ``` -------------------------------- ### Handle Camera Zoom Gesture Source: https://pub.dev/packages/camera_android/example Updates the camera zoom level based on multi-finger scaling gestures. Requires exactly two pointers on the screen. ```dart void _handleScaleStart(ScaleStartDetails details) { _baseScale = _currentScale; } Future _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 CameraPlatform.instance.setZoomLevel( controller!.cameraId, _currentScale, ); } ``` -------------------------------- ### Show Camera Exception Source: https://pub.dev/packages/camera_avfoundation/example Logs and displays a camera exception to the user via a snackbar. This is a helper function for error handling. ```dart void _showCameraException(CameraException e) { _logError(e.code, e.description); showInSnackBar('Error: ${e.code}\n${e.description}'); } ``` -------------------------------- ### Add camera_android Dependency Source: https://pub.dev/packages/camera_android/install Use this command to add the camera_android package to your Flutter project's dependencies. This command automatically updates your pubspec.yaml file. ```bash $ flutter pub add camera_android ``` -------------------------------- ### Displaying Captured Image on Web Source: https://pub.dev/packages/camera_web This snippet shows how to display a captured image on the web using Image.network. It contrasts with displaying images from local files on non-web platforms. ```dart final Image image; if (kIsWeb) { image = Image.network(capturedImage.path); } else { image = Image.file(File(capturedImage.path)); } ``` -------------------------------- ### Add camera_avfoundation to Flutter Project Source: https://pub.dev/packages/camera_avfoundation/install Use this command to add the camera_avfoundation package as a dependency in your Flutter project. This command automatically updates your pubspec.yaml file. ```bash $ flutter pub add camera_avfoundation ``` -------------------------------- ### Take Picture Source: https://pub.dev/packages/camera_avfoundation/example Initiates the process of taking a picture and saves the resulting XFile. Updates the UI with the saved image file path and disposes of any active video controller. ```dart void onTakePictureButtonPressed() { takePicture().then((XFile? file) { if (mounted) { setState(() { imageFile = file; videoController?.dispose(); videoController = null; }); if (file != null) { showInSnackBar('Picture saved to ${file.path}'); } } }); } ``` -------------------------------- ### Pause Video Recording Logic Source: https://pub.dev/packages/camera_avfoundation/example Contains the core logic for pausing video recording. It checks for camera initialization and handles potential exceptions. ```dart Future pauseVideoRecording() async { final CameraController? cameraController = controller; ``` -------------------------------- ### Import Camera Package in Dart Code Source: https://pub.dev/packages/camera/install Include this import statement in your Dart files to access the functionality provided by the camera plugin. ```dart import 'package:camera/camera.dart'; ``` -------------------------------- ### Camera Selection Row Source: https://pub.dev/packages/camera/example Widget to display available cameras and allow selection. If no cameras are found, it displays a 'No camera found.' message. Otherwise, it populates a list of camera descriptions. ```dart /// Display a row of toggle to select the camera (or a message if no camera is available). Widget _cameraTogglesRowWidget() { final toggles = []; 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( ``` -------------------------------- ### Set Exposure Mode and Offset Source: https://pub.dev/packages/camera_avfoundation/example Configures the camera's exposure mode and adjusts the exposure offset. Includes error handling for CameraExceptions. ```dart Future setExposureMode(ExposureMode mode) async { if (controller == null) { return; } try { await controller!.setExposureMode(mode); } on CameraException catch (e) { _showCameraException(e); rethrow; } } Future setExposureOffset(double offset) async { if (controller == null) { return; } setState(() { _currentExposureOffset = offset; }); try { offset = await controller!.setExposureOffset(offset); } on CameraException catch (e) { _showCameraException(e); rethrow; } } ``` -------------------------------- ### Display Thumbnail Widget Source: https://pub.dev/packages/camera_android/example Shows a thumbnail of the captured image or video. Supports both web (Image.network) and non-web (Image.file) image display, and video playback. ```dart Widget _thumbnailWidget() { final VideoPlayerController? localVideoController = videoController; return Expanded( child: Align( alignment: Alignment.centerRight, child: Row( mainAxisSize: MainAxisSize.min, children: [ 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.aspectRatio, child: VideoPlayer(localVideoController), ), ), ), ), ], ), ), ); } ``` -------------------------------- ### Handling App Lifecycle States with CameraController Source: https://pub.dev/packages/camera Override didChangeAppLifecycleState to manage camera controller resources during app lifecycle changes. Dispose the controller when the app is inactive and re-initialize when resumed. ```dart @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); } } ```