### Example: Custom Processing with XFileCapturedCallback Source: https://github.com/fluttercandies/flutter_wechat_camera_picker/blob/main/_autodocs/types.md Shows an example of performing custom processing on a captured file using the onXFileCaptured callback. This includes optional video compression and uploading, returning true to skip the default preview. ```dart final config = CameraPickerConfig( onXFileCaptured: (XFile file, CameraPickerViewType viewType) async { // Process file if (viewType == CameraPickerViewType.video) { final compressed = await compressVideo(file); await uploadToServer(compressed); } // Return true to skip preview return true; }, ); ``` -------------------------------- ### Example Usage of pushToViewer Source: https://github.com/fluttercandies/flutter_wechat_camera_picker/blob/main/_autodocs/api-reference/camera-picker-viewer.md Demonstrates how to call pushToViewer with necessary parameters to display the camera viewer for an image. ```dart final XFile capturedFile = /* ... */; final result = await CameraPickerViewer.pushToViewer( context, pickerConfig: const CameraPickerConfig(), viewType: CameraPickerViewType.image, previewXFile: capturedFile, ); ``` -------------------------------- ### CameraPicker.pickFromCamera Example Source: https://github.com/fluttercandies/flutter_wechat_camera_picker/blob/main/_autodocs/api-reference/camera-picker.md Demonstrates how to use the pickFromCamera static method to launch the camera interface and capture an asset. It shows how to configure recording duration and handle the result. ```dart final AssetEntity? result = await CameraPicker.pickFromCamera( context, pickerConfig: const CameraPickerConfig( enableRecording: true, maximumRecordingDuration: Duration(seconds: 30), ), ); if (result != null) { print('Captured asset: ${result.id}'); } ``` -------------------------------- ### Example Usage of sSwitchCameraLensDirectionLabel Source: https://github.com/fluttercandies/flutter_wechat_camera_picker/blob/main/_autodocs/api-reference/camera-picker-text-delegate.md Demonstrates how to use the sSwitchCameraLensDirectionLabel method to get the appropriate text for switching camera lens direction. The output varies based on the provided CameraLensDirection. ```dart final label = delegate.sSwitchCameraLensDirectionLabel(CameraLensDirection.front); // Chinese: "切换至前置摄像头" // English: "Switch to the front camera" // Vietnamese: "Chuyển sang camera trước" ``` -------------------------------- ### Example: Skip Preview with XFileCapturedCallback Source: https://github.com/fluttercandies/flutter_wechat_camera_picker/blob/main/_autodocs/types.md Demonstrates how to use the onXFileCaptured callback to skip the default preview screen. The callback prints the file path and returns true to indicate that the preview should be skipped. ```dart final config = CameraPickerConfig( onXFileCaptured: (XFile file, CameraPickerViewType viewType) { print('File captured: ${file.path}'); // Return true to skip default preview return true; }, ); ``` -------------------------------- ### CameraPickerState Usage Example Source: https://github.com/fluttercandies/flutter_wechat_camera_picker/blob/main/_autodocs/api-reference/camera-picker-state.md Demonstrates how to create a custom state class by extending `CameraPickerState` and overriding methods like `build` and `buildCaptureButton` to provide a tailored user interface and experience. ```APIDOC ## Usage Example This example shows how to create a custom `CameraPickerState` and use it with the `CameraPicker`. ```dart import 'package:flutter/material.dart'; import 'package:wechat_camera_picker/wechat_camera_picker.dart'; class CustomCameraPickerState extends CameraPickerState { @override Widget build(BuildContext context) { // Override build to create custom UI return Scaffold( body: buildPreview(), floatingActionButton: buildCaptureButton(), ); } @override Widget buildCaptureButton() { return FloatingActionButton( onPressed: () => handleCapture(), // Assuming handleCapture is available child: const Icon(Icons.camera), ); } } // To use the custom state: Future pickMedia(BuildContext context) async { final result = await CameraPicker.pickFromCamera( context, createPickerState: () => CustomCameraPickerState(), ); // Handle the result } ``` ``` -------------------------------- ### Example Error Flow in Picker Source: https://github.com/fluttercandies/flutter_wechat_camera_picker/blob/main/_autodocs/errors.md This example illustrates the error propagation flow within the picker. It shows how a user action can lead to an exception, which is then handled by the onError callback. ```dart // 1. User tries to take photo onTap: () async { try { // 2. Camera operations await controller.takePicture(); } catch (e, s) { // 3. Exception caught by picker handleErrorWithHandler(e, s, pickerConfig.onError); // 4. Calls onError if defined, else rethrows } } ``` -------------------------------- ### CameraPicker.themeData Example Source: https://github.com/fluttercandies/flutter_wechat_camera_picker/blob/main/_autodocs/api-reference/camera-picker.md Shows how to generate a ThemeData for the CameraPicker using the themeData static method. This allows customization of the picker's appearance with a primary color and light/dark variants. ```dart final AssetEntity? result = await CameraPicker.pickFromCamera( context, pickerConfig: CameraPickerConfig( theme: CameraPicker.themeData(Colors.blue), ), ); ``` -------------------------------- ### Basic Recording Progress Display Example Source: https://github.com/fluttercandies/flutter_wechat_camera_picker/blob/main/_autodocs/api-reference/camera-progress-button.md Demonstrates how to integrate CameraProgressButton into a recording interface. It uses a Stack to overlay the progress ring and a FloatingActionButton for recording control. The isAnimating property is tied to the recording state. ```dart class RecordingButton extends StatefulWidget { @override State createState() => _RecordingButtonState(); } class _RecordingButtonState extends State { bool isRecording = false; @override Widget build(BuildContext context) { return Stack( alignment: Alignment.center, children: [ // Progress ring (only visible when recording) CameraProgressButton( isAnimating: isRecording, size: const Size(80, 80), ringsWidth: 4, ringsColor: Colors.red, duration: const Duration(seconds: 30), ), // Record button FloatingActionButton( onPressed: _toggleRecording, child: Icon(isRecording ? Icons.stop : Icons.circle), ), ], ); } void _toggleRecording() { setState(() => isRecording = !isRecording); } } ``` -------------------------------- ### Custom Camera Picker State Example Source: https://github.com/fluttercandies/flutter_wechat_camera_picker/blob/main/_autodocs/api-reference/camera-picker-state.md Example of subclassing CameraPickerState to create a custom camera picker UI. This involves overriding the build and buildCaptureButton methods. The custom state can then be used when picking from the camera. ```dart class CustomCameraPickerState extends CameraPickerState { @override Widget build(BuildContext context) { // Override build to create custom UI return Scaffold( body: buildPreview(), floatingActionButton: buildCaptureButton(), ); } @override Widget buildCaptureButton() { return FloatingActionButton( onPressed: () => handleCapture(), child: const Icon(Icons.camera), ); } } // Use custom state final result = await CameraPicker.pickFromCamera( context, createPickerState: () => CustomCameraPickerState(), ); ``` -------------------------------- ### Handle File System Errors Source: https://github.com/fluttercandies/flutter_wechat_camera_picker/blob/main/_autodocs/errors.md Configure error handling for file system operations. This example demonstrates catching `FileSystemException` and logging the error without failing the picker. ```dart const config = CameraPickerConfig( onError: (Object error, StackTrace? stackTrace) { if (error is FileSystemException) { print('File operation failed: ${error.message}'); // Log but don't fail the picker } }, ); ``` -------------------------------- ### Overlay Integration with Auto-hiding Source: https://github.com/fluttercandies/flutter_wechat_camera_picker/blob/main/_autodocs/api-reference/camera-focus-point.md Provides an example of integrating CameraFocusPoint into an overlay, setting its position, and automatically removing it after a specified duration. ```dart // Display focus point at exposure point and auto-hide after 2 seconds void showFocusPoint(BuildContext context, Offset position) { final overlay = Overlay.of(context); final entry = OverlayEntry( builder: (_) => Positioned( left: position.dx - 25, top: position.dy - 25, child: const CameraFocusPoint( size: 50, color: Colors.white, ), ), ); overlay.insert(entry); Future.delayed(const Duration(seconds: 2), () { entry.remove(); }); } ``` -------------------------------- ### Enable Tap-to-Record Mode Source: https://github.com/fluttercandies/flutter_wechat_camera_picker/blob/main/_autodocs/configuration.md This configuration enables a tap-to-record mode for video, which requires `enableRecording` and `onlyEnableRecording` to be true. A single tap starts and stops recording. ```dart const CameraPickerConfig( enableRecording: true, onlyEnableRecording: true, enableTapRecording: true, ) ``` -------------------------------- ### Import WeChat Camera Picker Package Source: https://github.com/fluttercandies/flutter_wechat_camera_picker/blob/main/README.md Import the necessary package into your Dart code to start using its functionalities. ```dart import 'package:wechat_camera_picker/wechat_camera_picker.dart'; ``` -------------------------------- ### Log Errors and Show User Messages Source: https://github.com/fluttercandies/flutter_wechat_camera_picker/blob/main/_autodocs/errors.md Implement error logging for debugging and provide user-friendly messages. This example shows logging to a service and displaying a message to the user. ```dart CameraPickerConfig( onError: (error, stackTrace) { // Log to analytics logErrorToService(error, stackTrace); // Show user message showUserFriendlyError(error); }, ) ``` -------------------------------- ### Handle Camera Initialization Errors Source: https://github.com/fluttercandies/flutter_wechat_camera_picker/blob/main/_autodocs/errors.md Configure the `onError` callback to specifically handle `CameraException` during camera initialization. This example shows how to react to 'CameraAccessDenied'. ```dart const config = CameraPickerConfig( onError: (Object error, StackTrace? stackTrace) { if (error is CameraException) { switch (error.code) { case 'CameraAccessDenied': // Show permission denial UI showDialog( context: context, builder: (_) => AlertDialog( title: const Text('Camera Access Denied'), content: const Text('Please enable camera in settings.'), ), ); case 'CameraAccessDeniedWithoutPrompt': // Permission was never requested break; default: print('Unknown camera error: ${error.code}'); } } }, ); ``` -------------------------------- ### Custom File Handling with onEntitySaving Source: https://github.com/fluttercandies/flutter_wechat_camera_picker/blob/main/_autodocs/api-reference/camera-picker-config.md Implements custom file handling by overriding the default save behavior using `onEntitySaving`. This example also demonstrates popping the navigation stack after saving. ```dart File? capturedFile; final config = CameraPickerConfig( onEntitySaving: (BuildContext context, CameraPickerViewType viewType, File file) async { capturedFile = file; // Pop twice: once for viewer, once for picker Navigator.of(context)..pop()..pop(); }, ); final result = await CameraPicker.pickFromCamera(context, pickerConfig: config); print('Captured file: ${capturedFile?.path}'); ``` -------------------------------- ### Custom Spanish Camera Picker Text Delegate Source: https://github.com/fluttercandies/flutter_wechat_camera_picker/blob/main/_autodocs/api-reference/camera-picker-text-delegate.md An example of a custom CameraPickerTextDelegate implementation in Spanish. This class overrides various text properties and methods to provide localized strings for the camera picker. ```dart class SpanishCameraPickerTextDelegate extends CameraPickerTextDelegate { const SpanishCameraPickerTextDelegate(); @override String get languageCode => 'es'; @override String get confirm => 'Confirmar'; @override String get shootingTips => 'Toque para tomar foto.'; @override String get shootingWithRecordingTips => 'Toque para tomar foto. Mantenga presionado para grabar vídeo.'; @override String get shootingOnlyRecordingTips => 'Mantenga presionado para grabar vídeo.'; @override String get shootingTapRecordingTips => 'Toque para grabar vídeo.'; @override String get loadFailed => 'Error en la carga'; @override String get loading => 'Cargando...'; @override String get saving => 'Guardando...'; @override String sCameraLensDirectionLabel(CameraLensDirection value) { switch (value) { case CameraLensDirection.front: return 'frontal'; case CameraLensDirection.back: return 'trasera'; case CameraLensDirection.external: return 'externa'; } } @override String sSwitchCameraLensDirectionLabel(CameraLensDirection value) => 'Cambiar a cámara ${sCameraLensDirectionLabel(value)}'; @override String sFlashModeLabel(FlashMode mode) => 'Modo flash: ${mode.name}'; } // Usage final config = CameraPickerConfig( textDelegate: const SpanishCameraPickerTextDelegate(), ); ``` -------------------------------- ### didUpdateWidget Method Source: https://github.com/fluttercandies/flutter_wechat_camera_picker/blob/main/_autodocs/api-reference/camera-progress-button.md Responds to changes in the `isAnimating` property by starting or stopping the animation controller. ```dart @override void didUpdateWidget(CameraProgressButton oldWidget) { super.didUpdateWidget(oldWidget); if (widget.isAnimating != oldWidget.isAnimating) { if (widget.isAnimating) { progressController.forward(); } else { progressController.stop(); } } } ``` -------------------------------- ### Simple Camera Pick Usage Source: https://github.com/fluttercandies/flutter_wechat_camera_picker/blob/main/README.md Initiate the camera to pick media using the CameraPicker.pickFromCamera method. This is the most straightforward way to integrate camera functionality. ```dart final AssetEntity? entity = await CameraPicker.pickFromCamera(context); ``` -------------------------------- ### Assertion Rule Example Source: https://github.com/fluttercandies/flutter_wechat_camera_picker/blob/main/_autodocs/configuration.md Illustrates the assertion rule where `onlyEnableRecording: true` requires `enableRecording: true`. ```dart assert( enableRecording == true || onlyEnableRecording != true, 'Recording mode error.', ) ``` -------------------------------- ### Project File Structure Source: https://github.com/fluttercandies/flutter_wechat_camera_picker/blob/main/_autodocs/00-START-HERE.md Overview of the generated documentation file structure for the Flutter WeChat Camera Picker project. ```plaintext output/ ├── 00-START-HERE.md (this file) ├── README.md ← Start here ├── INDEX.md ← Find what you need ├── MANIFEST.md ← Verification & manifest ├── types.md ← Enum and type definitions ├── configuration.md ← Configuration reference ├── errors.md ← Error handling guide └── api-reference/ ← API documentation ├── camera-picker.md ├── camera-picker-config.md ├── camera-picker-state.md ├── camera-picker-viewer.md ├── camera-picker-viewer-state.md ├── camera-picker-page-route.md ├── camera-picker-text-delegate.md ├── camera-focus-point.md └── camera-progress-button.md ``` -------------------------------- ### initializeVideoPlayerController Source: https://github.com/fluttercandies/flutter_wechat_camera_picker/blob/main/_autodocs/api-reference/camera-picker-viewer-state.md Initializes the video player controller for video previews. It handles the creation of the controller, sets up listeners, and manages error states. Auto-plays the video if configured. ```APIDOC ## initializeVideoPlayerController() ### Description Initializes the `VideoPlayerController` for video previews. This method is called automatically during the `initState` lifecycle if the viewed asset is a video. It handles setting up the controller, managing playback state, and reporting initialization errors. ### Method ```dart Future initializeVideoPlayerController() ``` ### Behavior - Creates a `VideoPlayerController` using the `previewFile`. - Adds a listener to the controller to update the `isPlaying` state. - Sets `hasLoaded` to true upon successful initialization. - Sets `hasErrorWhenInitializing` to true if initialization fails. - Automatically plays and loops the video if `shouldAutoPreviewVideo` is true in the picker configuration. ### Called By - `initState` (when `widget.viewType` is `CameraPickerViewType.video`) ``` -------------------------------- ### Basic Photo Capture Source: https://github.com/fluttercandies/flutter_wechat_camera_picker/blob/main/_autodocs/api-reference/camera-picker-config.md Demonstrates the default configuration for capturing a photo. ```dart final config = const CameraPickerConfig(); final result = await CameraPicker.pickFromCamera(context, pickerConfig: config); ``` -------------------------------- ### Camera Picker Configuration Options Source: https://github.com/fluttercandies/flutter_wechat_camera_picker/blob/main/README.md This snippet outlines the available parameters for configuring the camera picker, including custom builders, save callbacks, error handlers, and permission options. ```APIDOC ## Camera Picker Configuration ### Description Provides a set of options to customize the camera picker's behavior and appearance. ### Parameters #### Optional Parameters - **foregroundBuilder** (`ForegroundBuilder?`) - A widget builder that overlays the entire camera preview. - **previewTransformBuilder** (`PreviewTransformBuilder?`) - A widget builder to transform the camera preview. - **onEntitySaving** (`EntitySaveCallback?`) - Callback for saving entities within the viewer. - **onError** (`CameraErrorHandler?`) - Handler for errors occurring during the picking process. - **onXFileCaptured** (`XFileCapturedCallback?`) - Callback when an XFile is captured by the camera. - **onMinimumRecordDurationNotMet** (`VoidCallback?`) - Callback when the minimum recording duration is not met. - **onPickConfirmed** (`void Function(AssetEntity)?`) - Callback when a picture is taken or a video is confirmed. - **permissionRequestOption** (`PermissionRequestOption?`) - Option for requesting permissions when saving captured files using the `photo_manager` package. ``` -------------------------------- ### playButtonCallback Source: https://github.com/fluttercandies/flutter_wechat_camera_picker/blob/main/_autodocs/api-reference/camera-picker-viewer-state.md Toggles the playback state of the video. If the video is playing, it pauses; if paused, it resumes. If the video has reached its end, it seeks to the beginning and starts playing. ```APIDOC ## playButtonCallback() ### Description Toggles the playback state of the video player. This method is typically called when a play/pause button is pressed. ### Method ```dart Future playButtonCallback() ``` ### Behavior - If the video is currently playing, it will be paused. - If the video is paused, it will resume playback from the current position. - If the video has finished playing, it will seek to the beginning and start playing again. ### Example Usage ```dart // In your UI widget: child: IconButton( onPressed: () => state.playButtonCallback(), icon: ValueListenableBuilder( valueListenable: state.isPlaying, builder: (_, playing, __) => Icon(playing ? Icons.pause : Icons.play_arrow), ), ), ``` ``` -------------------------------- ### Get Text Delegate from Locale Source: https://github.com/fluttercandies/flutter_wechat_camera_picker/blob/main/_autodocs/api-reference/camera-picker-text-delegate.md Returns the appropriate text delegate based on the provided locale. Falls back to Chinese if no matching language is found. ```dart CameraPickerTextDelegate cameraPickerTextDelegateFromLocale(Locale? locale) ``` ```dart final delegate = cameraPickerTextDelegateFromLocale(Locale('en', 'US')); print(delegate.confirm); // "Confirm" ``` -------------------------------- ### CameraPickerViewerState Constructor Source: https://github.com/fluttercandies/flutter_wechat_camera_picker/blob/main/_autodocs/api-reference/camera-picker-viewer-state.md Creates an instance of CameraPickerViewerState. No parameters are required for basic instantiation. Users can subclass this to create custom states. ```APIDOC ## CameraPickerViewerState() ### Description Initializes the state for the camera preview screen. This class manages video playback, file confirmation, and asset saving logic. ### Constructor ```dart CameraPickerViewerState() ``` ### Parameters None ``` -------------------------------- ### Pick from Camera with Configuration Source: https://github.com/fluttercandies/flutter_wechat_camera_picker/blob/main/README.md Use `CameraPickerConfig` to customize camera picking behaviors. This snippet shows how to initiate the camera picker with custom configurations. ```dart final AssetEntity? entity = await CameraPicker.pickFromCamera( context, pickerConfig: const CameraPickerConfig(), ); ``` -------------------------------- ### XFileCapturedCallback Source: https://github.com/fluttercandies/flutter_wechat_camera_picker/blob/main/_autodocs/types.md Callback triggered immediately after a file is captured by the camera, before the preview screen appears. It allows for immediate processing or skipping the default preview. ```APIDOC ## XFileCapturedCallback ### Description Callback triggered immediately after a file is captured by the camera, before the preview screen appears. It allows for immediate processing or skipping the default preview. ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Method Callback function ### Endpoint N/A ### Parameters - **XFile** (`XFile`) - Required - The newly captured file from camera. - **CameraPickerViewType** (`CameraPickerViewType`) - Required - Whether `image` or `video` was captured. ### Return Type `bool` - Whether the callback handled the file. - `true`: Default preview screen is skipped; callback should handle navigation. - `false`: Default preview screen is shown after callback returns. ### Request Example ```dart final config = CameraPickerConfig( onXFileCaptured: (XFile file, CameraPickerViewType viewType) { print('File captured: ${file.path}'); // Return true to skip default preview return true; }, ); ``` ### Response #### Success Response (N/A) N/A #### Response Example N/A ### Important Notes: - File is temporary; copy/save before returning. - Return `false` to show preview; confirm button will handle asset creation. - Return `true` to skip preview; you must handle file and navigation. - Different from `onEntitySaving` — this is before preview, that's before save. ### Used in: - [`CameraPickerConfig`](./api-reference/camera-picker-config.md) ### Import: `package:wechat_camera_picker/wechat_camera_picker.dart` ``` -------------------------------- ### Push CameraPickerViewer to Navigation Stack Source: https://github.com/fluttercandies/flutter_wechat_camera_picker/blob/main/_autodocs/api-reference/camera-picker-viewer.md Use this static method to display the viewer screen. It handles navigation and returns the selected asset or null if cancelled. Ensure context, pickerConfig, viewType, and previewXFile are provided. ```dart static Future pushToViewer( BuildContext context, { Key? key, required CameraPickerConfig pickerConfig, required CameraPickerViewType viewType, required XFile previewXFile, CameraPickerViewerState Function()? createViewerState, bool useRootNavigator = true, }) ``` -------------------------------- ### Basic Photo Capture and Video Recording Source: https://github.com/fluttercandies/flutter_wechat_camera_picker/blob/main/_autodocs/00-START-HERE.md Demonstrates how to pick a photo from the camera or enable video recording with a maximum duration. Ensure you have imported the necessary package. ```dart import 'package:wechat_camera_picker/wechat_camera_picker.dart'; // Take a photo final AssetEntity? result = await CameraPicker.pickFromCamera(context); // Or with video recording final result = await CameraPicker.pickFromCamera( context, pickerConfig: const CameraPickerConfig( enableRecording: true, maximumRecordingDuration: Duration(seconds: 30), ), ); if (result != null) { print('Asset captured: ${result.id}'); } ``` -------------------------------- ### Implement Graceful Error Handling Source: https://github.com/fluttercandies/flutter_wechat_camera_picker/blob/main/_autodocs/errors.md Always implement an error handler to prevent app crashes. This example shows the good practice of providing an onError callback to gracefully handle errors. ```dart // ❌ Bad: Errors are rethrown and crash app const config = CameraPickerConfig(); // ✅ Good: Graceful error handling const config = CameraPickerConfig( onError: (error, stackTrace) { print('Error: $error'); // Show user-friendly message }, ); ``` -------------------------------- ### Record Video from Camera Source: https://github.com/fluttercandies/flutter_wechat_camera_picker/blob/main/_autodocs/README.md This snippet demonstrates how to enable video recording with specific configurations like maximum duration. Ensure `enableRecording` and `enableAudio` are set to true for video capture. ```dart final result = await CameraPicker.pickFromCamera( context, pickerConfig: const CameraPickerConfig( enableRecording: true, enableAudio: true, maximumRecordingDuration: Duration(minutes: 1), ), ); ``` -------------------------------- ### Performance Tuning: Best Quality Settings Source: https://github.com/fluttercandies/flutter_wechat_camera_picker/blob/main/_autodocs/configuration.md Configure settings for the best possible quality by using the maximum resolution, enabling scaled preview, and enabling zoom features. ```dart const CameraPickerConfig( resolutionPreset: ResolutionPreset.max, // Maximum resolution enableScaledPreview: true, // Scale during capture enablePinchToZoom: true, // Enable zoom enablePullToZoomInRecord: true, // Enable pull zoom ) ``` -------------------------------- ### Custom Foreground Overlay Builder Source: https://github.com/fluttercandies/flutter_wechat_camera_picker/blob/main/_autodocs/types.md Use ForegroundBuilder to create custom overlay widgets on top of the camera preview. The controller is null during initialization, so handle this state gracefully. This builder is useful for displaying dynamic information like zoom level. ```dart typedef ForegroundBuilder = Widget Function( BuildContext context, CameraController? controller, ); final config = CameraPickerConfig( foregroundBuilder: (BuildContext context, CameraController? controller) { if (controller == null) { return const SizedBox.shrink(); } return Positioned( top: 20, right: 20, child: Text( 'Zoom: ${controller.value.isInitialized ? '${(controller.value.zoomLevel).toStringAsFixed(1)}x' : 'N/A'}', style: const TextStyle(color: Colors.white), ), ); }, ); ``` -------------------------------- ### CameraPickerState Constructor Source: https://github.com/fluttercandies/flutter_wechat_camera_picker/blob/main/_autodocs/api-reference/camera-picker-state.md Initializes the CameraPickerState. No parameters are required for the default constructor. Users can subclass this to create custom states. ```APIDOC ## CameraPickerState() ### Description Initializes the CameraPickerState. This is the base class for managing camera picker states. Users can subclass this to customize behavior and UI. ### Parameters This constructor does not take any parameters. ### Usage ```dart final cameraState = CameraPickerState(); ``` ``` -------------------------------- ### ForegroundBuilder Source: https://github.com/fluttercandies/flutter_wechat_camera_picker/blob/main/_autodocs/types.md Builds a custom overlay/foreground widget displayed on top of the camera preview. It allows for dynamic UI elements that can react to camera controller properties. ```APIDOC ## ForegroundBuilder ### Description Builds a custom overlay/foreground widget displayed on top of the camera preview. Use controller's properties to build responsive overlays. ### Signature ```dart typedef ForegroundBuilder = Widget Function( BuildContext context, CameraController? controller, ); ``` ### Parameters #### Parameters - **context** (`BuildContext`) - Current build context - **controller** (`CameraController?`) - Active camera controller. `null` until fully initialized. Use controller's properties to build responsive overlays. ### Return Type `Widget` — Custom overlay widget ### Behavior - Called to build a widget that overlays the camera preview - Controller is `null` during initialization; handle gracefully with null-aware code - Overlay is rendered in front of preview, useful for custom UI elements ### Example ```dart final config = CameraPickerConfig( foregroundBuilder: (BuildContext context, CameraController? controller) { if (controller == null) { return const SizedBox.shrink(); } return Positioned( top: 20, right: 20, child: Text( 'Zoom: ${controller.value.isInitialized ? '${(controller.value.zoomLevel).toStringAsFixed(1)}x' : 'N/A'}', style: const TextStyle(color: Colors.white), ), ); }, ); ``` ### Access Controller Properties - `controller.value.isInitialized` — Whether controller is ready - `controller.value.aspectRatio` — Camera aspect ratio - `controller.value.zoomLevel` — Current zoom level - `controller.value.flashMode` — Current flash mode - `controller.value.exposureMode` — Exposure mode ### Used in [`CameraPickerConfig`](./api-reference/camera-picker-config.md) ### Import `package:wechat_camera_picker/wechat_camera_picker.dart` ``` -------------------------------- ### CameraProgressButton Internal State Initialization Source: https://github.com/fluttercandies/flutter_wechat_camera_picker/blob/main/_autodocs/api-reference/camera-progress-button.md Initializes the AnimationController for the progress ring. The controller's duration is set based on the widget's duration parameter. Animation starts after the first frame if isAnimating is true. ```dart late final AnimationController progressController; @override void initState() { super.initState(); progressController = AnimationController( duration: widget.duration, vsync: this, ); ambiguate(WidgetsBinding.instance)?.addPostFrameCallback((_) { if (widget.isAnimating) { progressController.forward(); } }); } ``` -------------------------------- ### Initialize Video Player in initState Source: https://github.com/fluttercandies/flutter_wechat_camera_picker/blob/main/_autodocs/api-reference/camera-picker-viewer-state.md Initializes the video player controller in the initState method if the view type is video. Images bypass this initialization. ```dart @override void initState() { super.initState(); if (widget.viewType == CameraPickerViewType.video) { initializeVideoPlayerController(); } } ``` -------------------------------- ### Default Camera Picker Usage Source: https://github.com/fluttercandies/flutter_wechat_camera_picker/blob/main/_autodocs/api-reference/camera-picker-page-route.md Demonstrates the default way to pick from the camera using CameraPicker.pickFromCamera, which utilizes CameraPickerPageRoute internally. ```dart // CameraPicker.pickFromCamera uses this by default final result = await CameraPicker.pickFromCamera(context); ``` -------------------------------- ### CameraPickerPageRoute Methods Source: https://github.com/fluttercandies/flutter_wechat_camera_picker/blob/main/_autodocs/api-reference/camera-picker-page-route.md Explains the core methods of CameraPickerPageRoute, including `buildPage` for creating the route's content and `buildTransitions` for applying the slide animation. ```APIDOC ## CameraPickerPageRoute Methods ### buildPage ```dart @override Widget buildPage( BuildContext context, Animation animation, Animation secondaryAnimation, ) ``` Builds the route content by calling the `builder` function. **Returns:** `Widget` — The picker widget from builder ### buildTransitions ```dart @override Widget buildTransitions( BuildContext context, Animation animation, Animation secondaryAnimation, Widget child, ) ``` Builds the slide transition animation. Slides the content from bottom to top on entry, and from top to bottom on exit. **Animation:** - Entry: Slides from `Offset(0, 1)` (off-bottom) to `Offset.zero` (visible) - Exit: Reverses to `Offset(0, 1)` - Uses `transitionCurve` for the animation curve - Duration is `transitionDuration` **Returns:** `Widget` — The route with slide transition applied ### canTransitionFrom ```dart @override bool canTransitionFrom(TransitionRoute previousRoute) ``` Determines if a transition animation can occur when this route is pushed. **Returns:** `bool` — Result of `canTransitionFromPredicate`, or `false` if not defined ``` -------------------------------- ### Add Dependency to pubspec.yaml Source: https://github.com/fluttercandies/flutter_wechat_camera_picker/blob/main/README.md Add the wechat_camera_picker package to your project's pubspec.yaml file to include it as a dependency. ```yaml dependencies: wechat_camera_picker: ^latest_version ``` -------------------------------- ### Using CameraPickerConfig with a Custom Delegate Source: https://github.com/fluttercandies/flutter_wechat_camera_picker/blob/main/_autodocs/api-reference/camera-picker-text-delegate.md Shows how to configure the CameraPicker with a custom text delegate. This allows for localization and customization of the picker's UI text. ```dart final config = CameraPickerConfig( textDelegate: const EnglishCameraPickerTextDelegate(), ); final result = await CameraPicker.pickFromCamera( context, pickerConfig: config, ); ``` -------------------------------- ### CameraPickerConfig Constructor Source: https://github.com/fluttercandies/flutter_wechat_camera_picker/blob/main/_autodocs/api-reference/camera-picker-config.md This constructor allows for the configuration of various aspects of the camera picker, such as recording capabilities, gesture controls, preview behavior, and theme customization. ```APIDOC ## CameraPickerConfig Constructor ### Description Initializes a `CameraPickerConfig` object with customizable settings for the camera picker. ### Parameters #### Recording Configuration - **enableRecording** (`bool`) - Optional - Whether video recording is available. Enables long-press to record. Defaults to `false`. - **onlyEnableRecording** (`bool`) - Optional - If `true`, only video recording is available (photography disabled). Requires `enableRecording: true`. Defaults to `false`. - **enableTapRecording** (`bool`) - Optional - If `true`, single tap starts recording. Only works with `onlyEnableRecording: true`. Defaults to `false`. - **enableAudio** (`bool`) - Optional - Whether audio is recorded along with video. Defaults to `true`. - **maximumRecordingDuration** (`Duration?`) - Optional - Maximum video length. `null` allows unlimited recording. Defaults to `Duration(seconds: 15)`. - **minimumRecordingDuration** (`Duration`) - Optional - Minimum video length. Cannot be lower than 1 second. Defaults to `Duration(seconds: 1)`. #### Camera Control & Capture - **enableSetExposure** (`bool`) - Optional - Whether users can tap to set exposure point. Defaults to `true`. - **enableExposureControlOnPoint** (`bool`) - Optional - Whether exposure value can be adjusted via slider at set point. Defaults to `true`. - **enablePinchToZoom** (`bool`) - Optional - Whether users can pinch to zoom camera. Defaults to `true`. - **enablePullToZoomInRecord** (`bool`) - Optional - Whether users can drag up to zoom while recording video. Defaults to `true`. - **enableScaledPreview** (`bool`) - Optional - Whether camera preview scales during photo capture. Defaults to `false`. - **resolutionPreset** (`ResolutionPreset`) - Optional - Camera resolution quality: veryLow, low, medium, high, veryHigh, ultraHigh, max. Defaults to `ResolutionPreset.ultraHigh`. - **preferredLensDirection** (`CameraLensDirection`) - Optional - Initial camera: front, back, or external. Defaults to `CameraLensDirection.back`. - **preferredFlashMode** (`FlashMode`) - Optional - Initial flash mode: off, auto, always, torch. Defaults to `FlashMode.off`. - **lockCaptureOrientation** (`DeviceOrientation?`) - Optional - Lock device orientation during capture. `null` allows rotation. Defaults to `null`. - **cameraQuarterTurns** (`int`) - Optional - Clockwise 90-degree rotations for camera view (0-3). Defaults to `0`. - **imageFormatGroup** (`ImageFormatGroup`) - Optional - Raw image output format. Defaults to `ImageFormatGroup.unknown`. #### Preview & File Handling - **shouldDeletePreviewFile** (`bool`) - Optional - Delete preview file when picker is closed. Defaults to `false`. - **shouldAutoPreviewVideo** (`bool`) - Optional - Auto-play video in preview screen. Defaults to `true`. #### Theme & Localization - **theme** (`ThemeData?`) - Optional - Custom theme. If `null`, uses default WeChat-based theme. Defaults to `null`. - **textDelegate** (`CameraPickerTextDelegate?`) - Optional - Custom text labels. If `null`, uses system locale or Chinese. Defaults to `null`. #### Callbacks - **onEntitySaving** (`EntitySaveCallback?`) - Optional - Callback when an entity is being saved. - **onError** (`CameraErrorHandler?`) - Optional - Callback for camera errors. - **onXFileCaptured** (`XFileCapturedCallback?`) - Optional - Callback when an XFile is captured. - **onMinimumRecordDurationNotMet** (`VoidCallback?`) - Optional - Callback when the minimum record duration is not met. - **onPickConfirmed** (`void Function(AssetEntity)?`) - Optional - Callback when picking is confirmed. - **permissionRequestOption** (`PermissionRequestOption?`) - Optional - Options for requesting permissions. ``` -------------------------------- ### CameraPickerPageRoute Constructor and Parameters Source: https://github.com/fluttercandies/flutter_wechat_camera_picker/blob/main/_autodocs/api-reference/camera-picker-page-route.md Details the constructor for CameraPickerPageRoute and its configurable parameters for customizing the page route transition. ```APIDOC ## CameraPickerPageRoute Constructor `CameraPickerPageRoute` is a custom `PageRoute` implementation that provides a slide-up transition animation for the camera picker. It handles the visual transition as the picker enters and exits the screen. **Import Path:** `package:wechat_camera_picker/wechat_camera_picker.dart` ### Parameters | Parameter | Type | Default | Description | |---|---|---|---| | builder | `WidgetBuilder` | — | Required. Widget builder function for the route | | transitionCurve | `Curve` | `Curves.easeIn` | Animation curve for the transition | | transitionDuration | `Duration` | `300ms` | Animation duration | | barrierColor | `Color?` | `null` | Color of the barrier below the route | | barrierDismissible | `bool` | `false` | Whether tapping barrier dismisses the route | | barrierLabel | `String?` | `null` | Accessibility label for the barrier | | maintainState | `bool` | `true` | Whether to maintain state when route is pushed | | opaque | `bool` | `true` | Whether this route is fully opaque | | canTransitionFromPredicate | `bool Function(TransitionRoute)?` | `null` | Custom predicate for transition eligibility | | fullscreenDialog | `bool` | `false` | Whether to display as fullscreen dialog | | settings | `RouteSettings?` | `null` | Route settings and name | ``` -------------------------------- ### Common Issue: `enableTapRecording` without `onlyEnableRecording` Source: https://github.com/fluttercandies/flutter_wechat_camera_picker/blob/main/_autodocs/configuration.md Shows the incorrect and correct configuration for enabling tap-to-record. Both `onlyEnableRecording` and `enableTapRecording` must be true. ```dart // ❌ Wrong const CameraPickerConfig( enableRecording: true, enableTapRecording: true, ) // ✅ Correct const CameraPickerConfig( enableRecording: true, onlyEnableRecording: true, enableTapRecording: true, ) ``` -------------------------------- ### Pick Photo from Camera (Default) Source: https://github.com/fluttercandies/flutter_wechat_camera_picker/blob/main/_autodocs/README.md This snippet shows the default way to pick a photo from the camera. The result is an AssetEntity which can be used to access the file and its properties. ```dart final result = await CameraPicker.pickFromCamera(context); if (result != null) { // Use result AssetEntity } ``` -------------------------------- ### CameraPickerConfig Constructor Source: https://github.com/fluttercandies/flutter_wechat_camera_picker/blob/main/_autodocs/api-reference/camera-picker-config.md Defines all configurable options for the camera picker, including recording, exposure, zoom, resolution, and theme. ```dart const CameraPickerConfig({ bool enableRecording = false, bool onlyEnableRecording = false, bool enableTapRecording = false, bool enableAudio = true, bool enableSetExposure = true, bool enableExposureControlOnPoint = true, bool enablePinchToZoom = true, bool enablePullToZoomInRecord = true, bool enableScaledPreview = false, bool shouldDeletePreviewFile = false, bool shouldAutoPreviewVideo = true, Duration? maximumRecordingDuration = const Duration(seconds: 15), Duration minimumRecordingDuration = const Duration(seconds: 1), ThemeData? theme, CameraPickerTextDelegate? textDelegate, int cameraQuarterTurns = 0, ResolutionPreset resolutionPreset = ResolutionPreset.ultraHigh, ImageFormatGroup imageFormatGroup = ImageFormatGroup.unknown, CameraLensDirection preferredLensDirection = CameraLensDirection.back, FlashMode preferredFlashMode = FlashMode.off, DeviceOrientation? lockCaptureOrientation, ForegroundBuilder? foregroundBuilder, PreviewTransformBuilder? previewTransformBuilder, EntitySaveCallback? onEntitySaving, CameraErrorHandler? onError, XFileCapturedCallback? onXFileCaptured, VoidCallback? onMinimumRecordDurationNotMet, void Function(AssetEntity)? onPickConfirmed, PermissionRequestOption? permissionRequestOption, }) ``` -------------------------------- ### Handle Video Controller Initialization Errors Source: https://github.com/fluttercandies/flutter_wechat_camera_picker/blob/main/_autodocs/errors.md Implement error handling for video player controller initialization failures. This snippet shows how to catch `PlatformException` and log the error message. ```dart const config = CameraPickerConfig( onError: (Object error, StackTrace? stackTrace) { if (error is PlatformException) { print('Video playback error: ${error.message}'); // Show fallback UI (e.g., "Video cannot be previewed") } }, ); ``` -------------------------------- ### Configure High Resolution for Quality Source: https://github.com/fluttercandies/flutter_wechat_camera_picker/blob/main/_autodocs/configuration.md Set the camera to capture at the maximum available resolution for the highest possible image quality. ```dart const CameraPickerConfig( resolutionPreset: ResolutionPreset.max, ) ``` -------------------------------- ### createAssetEntityAndPop Source: https://github.com/fluttercandies/flutter_wechat_camera_picker/blob/main/_autodocs/api-reference/camera-picker-viewer-state.md Saves the captured file and returns the created AssetEntity. It supports custom saving logic via callbacks or a default saving mechanism using the photo_manager library. ```APIDOC ## createAssetEntityAndPop() ### Description Handles the confirmation of a captured media file. This method is responsible for saving the file, either through a custom callback (`onEntitySaving`) or a default mechanism, and then returning the created `AssetEntity` to the calling context. It also includes error handling and prevents concurrent save operations. ### Method ```dart Future createAssetEntityAndPop() ``` ### Behavior 1. **Concurrency Check**: Prevents multiple save operations by checking the `isSavingEntity` flag. 2. **Set Saving State**: Sets `isSavingEntity` to `true` to indicate a save operation is in progress. 3. **Custom Saving**: If `onEntitySaving` is provided in the picker configuration, it calls this callback with the captured file. The callback is expected to handle the saving process and return an `AssetEntity`. 4. **Default Saving**: If `onEntitySaving` is not provided, it uses the default mechanism to create an `AssetEntity` via the `photo_manager` library. 5. **Return Entity**: Once the asset is saved (either custom or default), it pops the current route and returns the `AssetEntity`. 6. **Error Handling**: Catches any exceptions during the process and invokes the `onError` handler if configured. 7. **Cleanup**: Resets `isSavingEntity` to `false` in a `finally` block to ensure the flag is always cleared, even if errors occur. ### Called By - Typically called by the 'Confirm' or 'Done' button on the preview screen. ### Error Handling - Catches exceptions and calls the `onError` handler provided in `CameraPickerConfig`. - Ensures `isSavingEntity` is reset to `false`. ``` -------------------------------- ### CameraPickerPageRoute Configuration Source: https://github.com/fluttercandies/flutter_wechat_camera_picker/blob/main/_autodocs/api-reference/camera-picker-page-route.md Demonstrates how to use CameraPickerPageRoute to customize the camera picker's route, including barrier color, dismissibility, and label. ```APIDOC ## CameraPicker.pickFromCamera with CustomPageRoute ### Description Allows users to pick media from the camera with a customizable route. ### Method `CameraPicker.pickFromCamera` ### Parameters - `context` (BuildContext) - Required - The build context for the widget. - `pageRouteBuilder` (Function) - Optional - A function that returns a `PageRoute` for the camera picker. - This function receives the picker widget and should return a `CameraPickerPageRoute` or similar. ### Example Usage ```dart final result = await CameraPicker.pickFromCamera( context, pageRouteBuilder: (Widget picker) => CameraPickerPageRoute( builder: (_) => picker, barrierColor: Colors.black54, barrierDismissible: true, barrierLabel: 'Dismiss camera picker', ), ); ``` ## CameraPickerPageRoute ### Description A `PageRoute` specifically for the camera picker, allowing for detailed customization of the transition and barrier. ### Type Parameter - ``: Specifies the return type of the route. Typically `AssetEntity` for the camera picker. ### Constructor Parameters - `builder` (Widget Function) - Required - Builds the content of the route. - `transitionDuration` (Duration) - Optional - The duration of the transition. Defaults to 300ms. - `transitionCurve` (Curve) - Optional - The curve of the transition. Defaults to `Curves.easeIn`. - `barrierColor` (Color) - Optional - The color of the barrier behind the route. - `barrierDismissible` (bool) - Optional - Whether the barrier is dismissible. Defaults to `false`. - `barrierLabel` (String) - Optional - The accessibility label for the barrier. - `opaque` (bool) - Optional - Whether the route is opaque. Defaults to `true`. - `maintainState` (bool) - Optional - Whether to maintain the state of the route. Defaults to `true`. ### Default Behavior When `pageRouteBuilder` is not provided to `pickFromCamera`, `CameraPickerPageRoute` is used with the following defaults: ```dart CameraPickerPageRoute( builder: (_) => picker, transitionDuration: const Duration(milliseconds: 300), transitionCurve: Curves.easeIn, barrierDismissible: false, opaque: true, maintainState: true, ) ``` ### Animation Curves Reference Common curves for `transitionCurve` include: - `Curves.easeIn`: Accelerates from bottom. - `Curves.easeOut`: Decelerates as it reaches top. - `Curves.easeInOut`: Accelerates then decelerates. - `Curves.linear`: Constant speed. - `Curves.elasticOut`: Bouncy effect. - `Curves.bounceOut`: Bounces at end. ``` -------------------------------- ### pickFromCamera Source: https://github.com/fluttercandies/flutter_wechat_camera_picker/blob/main/_autodocs/api-reference/camera-picker.md Creates and displays the camera picker interface. Returns an AssetEntity? when a photo or video is confirmed, or null if the user cancels. ```APIDOC ## pickFromCamera ```dart static Future pickFromCamera( BuildContext context, { CameraPickerConfig pickerConfig = const CameraPickerConfig(), CameraPickerState Function()? createPickerState, bool useRootNavigator = true, CameraPickerPageRoute Function(Widget picker)? pageRouteBuilder, Locale? locale, } ``` ### Description Launches the camera interface for capturing photos or videos. The user can confirm their selection or cancel the operation. ### Method `static Future` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None #### Parameters * **context** (`BuildContext`) - Required - Current build context for navigation. * **pickerConfig** (`CameraPickerConfig`) - Optional - Configuration for the picker behavior. Defaults to `const CameraPickerConfig()`. * **createPickerState** (`CameraPickerState Function()?`) - Optional - Custom state factory for overriding UI. * **useRootNavigator** (`bool`) - Optional - Whether to use the root navigator for pushing the route. Defaults to `true`. * **pageRouteBuilder** (`CameraPickerPageRoute Function(Widget)?`) - Optional - Custom route builder. If `null`, uses default slide transition. * **locale** (`Locale?`) - Optional - Override locale for text delegates. ### Request Example ```dart final AssetEntity? result = await CameraPicker.pickFromCamera( context, pickerConfig: const CameraPickerConfig( enableRecording: true, maximumRecordingDuration: Duration(seconds: 30), ), ); if (result != null) { print('Captured asset: ${result.id}'); } ``` ### Response #### Success Response (200) * **AssetEntity?** - The captured asset entity if a photo or video is successfully taken and confirmed, otherwise `null` if the user cancels. #### Response Example ```json { "id": "123", "type": "image", "name": "IMG_20230101.jpg", "size": 102400, "width": 1920, "height": 1080, "duration": 0, "creationTime": 1672531200000, "modifiedTime": 1672531200000, "latitude": 37.7749, "longitude": -122.4194, "isFavorite": false, "mimeType": "image/jpeg" } ``` ``` -------------------------------- ### Enable Preview File Deletion Source: https://github.com/fluttercandies/flutter_wechat_camera_picker/blob/main/_autodocs/configuration.md Set `shouldDeletePreviewFile` to `true` to ensure preview files are deleted after use. This is `false` by default. ```dart const CameraPickerConfig( shouldDeletePreviewFile: true, ) ``` -------------------------------- ### Common Issue: `onlyEnableRecording` without `enableRecording` Source: https://github.com/fluttercandies/flutter_wechat_camera_picker/blob/main/_autodocs/configuration.md Demonstrates the incorrect and correct way to enable `onlyEnableRecording`. It must be preceded by `enableRecording: true`. ```dart // ❌ Wrong const CameraPickerConfig( onlyEnableRecording: true, ) // ✅ Correct const CameraPickerConfig( enableRecording: true, onlyEnableRecording: true, ) ```