### Run Example App Source: https://github.com/johnny-bytes/native_file_preview/blob/main/README.md Navigate to the example directory and run the Flutter app to see the plugin in action. This demonstrates various usage scenarios, error handling, and platform-specific behaviors. ```bash cd example flutter run ``` -------------------------------- ### Custom Platform Implementation Example Source: https://github.com/johnny-bytes/native_file_preview/blob/main/_autodocs/api-reference/NativeFilePreviewPlatform.md Demonstrates how to create and register a custom implementation of the NativeFilePreviewPlatform interface. ```APIDOC ## Default Implementation The default implementation is `MethodChannelNativeFilePreview`, which communicates with native code via a method channel named `native_file_preview`. #### Example of Creating a Custom Platform Implementation ```dart import 'package:native_file_preview/native_file_preview_platform_interface.dart'; class CustomNativeFilePreview extends NativeFilePreviewPlatform { @override Future getPlatformVersion() async { // Custom implementation return 'custom_1.0.0'; } @override Future previewFile(String filePath) async { // Custom implementation // Could use a different communication method, caching strategy, etc. } } // Register the custom implementation void main() { NativeFilePreviewPlatform.instance = CustomNativeFilePreview(); runApp(MyApp()); } ``` ``` -------------------------------- ### Preview File Example Source: https://github.com/johnny-bytes/native_file_preview/blob/main/_autodocs/api-reference/NativeFilePreview.md Demonstrates how to use the previewFile method to open a local file. Includes error handling for PlatformException. ```dart import 'package:native_file_preview/native_file_preview.dart'; class FilePreviewScreen extends StatefulWidget { @override _FilePreviewScreenState createState() => _FilePreviewScreenState(); } class _FilePreviewScreenState extends State { final _nativeFilePreview = NativeFilePreview(); void _previewFile() async { try { // Preview a local file await _nativeFilePreview.previewFile('/path/to/document.pdf'); } on PlatformException catch (e) { _showErrorDialog('Preview Error', e.code, e.message); } } void _showErrorDialog(String title, String code, String? message) { showDialog( context: context, builder: (context) => AlertDialog( title: Text(title), content: Text('Error: $code\n${message ?? "Unknown error"}'), actions: [ TextButton( onPressed: () => Navigator.pop(context), child: Text('OK'), ), ], ), ); } @override Widget build(BuildContext context) { return ElevatedButton( onPressed: _previewFile, child: Text('Preview PDF'), ); } } ``` -------------------------------- ### Development Setup - Git Workflow Source: https://github.com/johnny-bytes/native_file_preview/blob/main/README.md Follow these steps to set up the development environment, contribute changes, and submit pull requests for the native_file_preview plugin. ```bash git checkout -b feature/amazing-feature ``` ```bash git commit -m 'Add some amazing feature' ``` ```bash git push origin feature/amazing-feature ``` -------------------------------- ### Custom Platform Implementation Example Source: https://github.com/johnny-bytes/native_file_preview/blob/main/_autodocs/api-reference/NativeFilePreviewPlatform.md Demonstrates how to create and register a custom implementation of NativeFilePreviewPlatform, overriding its abstract methods. ```dart import 'package:native_file_preview/native_file_preview_platform_interface.dart'; class CustomNativeFilePreview extends NativeFilePreviewPlatform { @override Future getPlatformVersion() async { // Custom implementation return 'custom_1.0.0'; } @override Future previewFile(String filePath) async { // Custom implementation // Could use a different communication method, caching strategy, etc. } } // Register the custom implementation void main() { NativeFilePreviewPlatform.instance = CustomNativeFilePreview(); runApp(MyApp()); } ``` -------------------------------- ### Present Modal Preview Example Source: https://github.com/johnny-bytes/native_file_preview/blob/main/_autodocs/api-reference/NativeFileViewerPreviewViewController-iOS.md Demonstrates how to instantiate and present the NativeFileViewerPreviewViewController modally, providing a data source and a completion handler that prints a message when the preview is dismissed. ```swift let previewController = NativeFileViewerPreviewViewController() previewController.dataSource = someDataSource previewController.presentModal(viewController: self) { result in print("Preview dismissed") // result is nil } ``` -------------------------------- ### FlutterMethodCall Usage Example Source: https://github.com/johnny-bytes/native_file_preview/blob/main/_autodocs/types.md Demonstrates how to handle incoming method calls and access their method name and arguments. ```dart void handle(FlutterMethodCall call, FlutterResult result) { // call.method: "previewFile" // call.arguments: {"file": "/path/to/file.pdf"} } ``` -------------------------------- ### Get Platform Version Example Source: https://github.com/johnny-bytes/native_file_preview/blob/main/_autodocs/api-reference/NativeFilePreview.md Retrieves and prints the platform version using the getPlatformVersion method. ```dart final version = await _nativeFilePreview.getPlatformVersion(); print('Platform Version: $version'); ``` -------------------------------- ### Preview File Example Flow Source: https://github.com/johnny-bytes/native_file_preview/blob/main/_autodocs/api-reference/NativeFilePreviewPlugin-iOS.md Illustrates the interaction between the Dart layer and the Swift plugin for previewing a file. Shows the method call from Dart and how the Swift plugin receives and processes it. ```swift // Dart layer calls: // await NativeFilePreview().previewFile('/path/to/document.pdf'); // Swift receives: FlutterMethodCall( method: "previewFile", arguments: ["file": "/path/to/document.pdf"] ) // Plugin processes: // 1. Validates file path is not nil // 2. Converts "/path/to/document.pdf" to URL // 3. Checks file exists and is readable // 4. Creates NativeFileViewerPreview instance // 5. Gets active view controller // 6. Presents preview controller modally // 7. Calls result(nil) when preview dismisses ``` -------------------------------- ### Create and Start Intent Source: https://github.com/johnny-bytes/native_file_preview/blob/main/_autodocs/types.md Construct an Intent object to perform an action, such as viewing a file. Use setDataAndType() to specify the URI and MIME type, and addFlags() to set necessary permissions and activity behaviors. ```kotlin class Intent(action: String?, uri: Uri?) { fun setDataAndType(uri: Uri?, type: String?): Intent fun addFlags(flags: Int): Intent } ``` ```kotlin val intent = Intent(Intent.ACTION_VIEW).apply { setDataAndType(uri, mimeType ?: "*/*") addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION) addFlags(Intent.FLAG_ACTIVITY_NEW_TASK) } activity.startActivity(intent) ``` -------------------------------- ### MethodChannel Usage Example Source: https://github.com/johnny-bytes/native_file_preview/blob/main/_autodocs/types.md Demonstrates invoking a method on the native platform using a MethodChannel. Ensure the channel name matches the native implementation. ```dart final methodChannel = const MethodChannel('native_file_preview'); Future previewFile(String filePath) async { await methodChannel.invokeMethod('previewFile', {'file': filePath}); } ``` -------------------------------- ### Correct Implementation of NativeFilePreviewPlatform Source: https://github.com/johnny-bytes/native_file_preview/blob/main/_autodocs/api-reference/Platform-Interface-Pattern.md Shows an example of a correctly implemented subclass that provides the required token to the superclass constructor and can be assigned to the platform instance. ```dart class CorrectImpl extends NativeFilePreviewPlatform { CorrectImpl() : super(token: NativeFilePreviewPlatform._token); // ✓ Has token access // ... } NativeFilePreviewPlatform.instance = CorrectImpl(); // ✓ Works ``` -------------------------------- ### Run flutter pub get Source: https://github.com/johnny-bytes/native_file_preview/blob/main/README.md After adding the dependency to pubspec.yaml, run this command in your terminal to fetch the package. ```bash flutter pub get ``` -------------------------------- ### File Selection and Preview in Flutter Source: https://github.com/johnny-bytes/native_file_preview/blob/main/README.md An advanced example showing how to use the file_picker package to let the user select a file, then preview it using NativeFilePreview. Includes error handling for both picking and previewing. ```dart import 'package:native_file_preview/native_file_preview.dart'; import 'package:file_picker/file_picker.dart'; class AdvancedFilePreview extends StatefulWidget { @override _AdvancedFilePreviewState createState() => _AdvancedFilePreviewState(); } class _AdvancedFilePreviewState extends State { final _nativeFilePreview = NativeFilePreview(); Future _pickAndPreviewFile() async { try { FilePickerResult? result = await FilePicker.platform.pickFiles(); if (result != null) { String filePath = result.files.single.path!; await _nativeFilePreview.previewFile(filePath); } } on PlatformException catch (e) { _showErrorDialog('Preview Error', e.message ?? 'Unknown error'); } catch (e) { _showErrorDialog('Unexpected Error', e.toString()); } } void _showErrorDialog(String title, String message) { showDialog( context: context, builder: (context) => AlertDialog( title: Text(title), content: Text(message), actions: [ TextButton( onPressed: () => Navigator.of(context).pop(), child: Text('OK'), ), ], ), ); } @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar(title: Text('Advanced File Preview')), body: Center( child: ElevatedButton( onPressed: _pickAndPreviewFile, child: Text('Pick and Preview File'), ), ), ); } } ``` -------------------------------- ### PlatformException Usage Example Source: https://github.com/johnny-bytes/native_file_preview/blob/main/_autodocs/types.md Shows how to catch and handle PlatformExceptions when method calls to the native layer fail. ```dart try { await nativeFilePreview.previewFile(filePath); } on PlatformException catch (e) { print('Error: ${e.code} - ${e.message}'); } ``` -------------------------------- ### Integration Test Setup Source: https://github.com/johnny-bytes/native_file_preview/blob/main/_autodocs/configuration.md Boilerplate for setting up integration tests with Flutter. Ensure integration_test package is initialized. ```dart import 'package:integration_test/integration_test.dart'; void main() { IntegrationTestWidgetsFlutterBinding.ensureInitialized(); testWidgets('Preview file integration test', (WidgetTester tester) async { // Your test code here }); } ``` -------------------------------- ### Create ACTION_VIEW Intent for File Preview Source: https://github.com/johnny-bytes/native_file_preview/blob/main/_autodocs/api-reference/NativeFilePreviewPlugin-Android.md Construct an Intent with ACTION_VIEW to open a file with the appropriate application. Use FLAG_GRANT_READ_URI_PERMISSION for temporary read access and FLAG_ACTIVITY_NEW_TASK to start in a new task. ```kotlin val intent = Intent(Intent.ACTION_VIEW).apply { setDataAndType(uri, mimeType ?: "*/*") addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION) addFlags(Intent.FLAG_ACTIVITY_NEW_TASK) } activity.startActivity(intent) ``` -------------------------------- ### iOS Swift XCTest Example Source: https://github.com/johnny-bytes/native_file_preview/blob/main/_autodocs/api-reference/Platform-Interface-Pattern.md An example of a unit test for the iOS native code using Swift's XCTest framework. This snippet illustrates testing file validation logic within the `NativeFilePreviewPlugin`. ```swift func testFileValidation() { let plugin = NativeFilePreviewPlugin() // Test with mock file manager } ``` -------------------------------- ### Android Kotlin JUnit Example Source: https://github.com/johnny-bytes/native_file_preview/blob/main/_autodocs/api-reference/Platform-Interface-Pattern.md An example of a unit test for the Android native code using Kotlin's JUnit framework. This snippet demonstrates testing a scenario like file not found within the `NativeFilePreviewPlugin`. ```kotlin @Test fun testFileNotFound() { val plugin = NativeFilePreviewPlugin() // Test with mock file } ``` -------------------------------- ### Get Default Platform Instance Source: https://github.com/johnny-bytes/native_file_preview/blob/main/_autodocs/api-reference/NativeFilePreviewPlatform.md Retrieves the default platform implementation instance. Used to access platform-specific file preview methods. ```dart static NativeFilePreviewPlatform get instance => _instance ``` ```dart // Get the current platform instance final platform = NativeFilePreviewPlatform.instance; final version = await platform.getPlatformVersion(); ``` -------------------------------- ### Future Example Usage Source: https://github.com/johnny-bytes/native_file_preview/blob/main/_autodocs/types.md Illustrates different ways to work with Futures, including awaiting completion, handling results with .then(), and combining multiple futures with Future.wait(). ```dart // Await a future await nativeFilePreview.previewFile(filePath); // Handle with .then() nativeFilePreview.previewFile(filePath).then((_) { print('Preview completed'); }); // Combine futures Future.wait([ nativeFilePreview.previewFile(file1), nativeFilePreview.previewFile(file2), ]); ``` -------------------------------- ### Android File Paths Configuration Source: https://github.com/johnny-bytes/native_file_preview/blob/main/README.md Define accessible file paths for the FileProvider in res/xml/file_paths.xml. This example grants access to files and cache directories. ```xml ``` -------------------------------- ### NativeFilePreview Class Source: https://github.com/johnny-bytes/native_file_preview/blob/main/_autodocs/OVERVIEW.md The main entry point for the Native File Preview plugin. It provides methods to preview files and get the platform version. ```APIDOC ## Class NativeFilePreview ### Description Provides methods to interact with the native file preview functionality. ### Methods #### `previewFile(String filePath)` - **Description**: Opens a native preview for the file specified by the `filePath`. - **Parameters**: - `filePath` (String) - Required - The path to the file to preview. - **Returns**: `Future` #### `getPlatformVersion()` - **Description**: Retrieves the version of the platform (iOS or Android) the plugin is running on. - **Parameters**: None - **Returns**: `Future` - The platform version string, or null if it cannot be determined. ``` -------------------------------- ### NativeFilePreviewPlatform Interface Source: https://github.com/johnny-bytes/native_file_preview/blob/main/_autodocs/api-reference/Platform-Interface-Pattern.md The abstract interface defines the contract for platform-specific implementations of native file preview functionality. It includes methods for getting the platform version and previewing files. ```APIDOC ## NativeFilePreviewPlatform ### Description An abstract interface defining the methods that platform-specific implementations must provide for native file preview functionality. ### Methods #### `getPlatformVersion()` - **Description**: Retrieves the version of the native platform. - **Returns**: A `Future` representing the platform version. #### `previewFile(String filePath)` - **Description**: Initiates the preview of a file at the given file path. - **Parameters**: - `filePath` (String) - Required - The path to the file to be previewed. - **Returns**: A `Future` indicating the completion of the preview operation. ``` -------------------------------- ### Mock Method Channel for Unit Tests Source: https://github.com/johnny-bytes/native_file_preview/blob/main/_autodocs/configuration.md Use this setup to mock the method channel for unit testing the plugin's implementation. It allows simulating method calls and their responses. ```dart import 'package:native_file_preview/native_file_preview_method_channel.dart'; import 'package:flutter_test/flutter_test.dart'; void main() { test('Example test setup', () async { final implementation = MethodChannelNativeFilePreview(); // Mock the channel implementation.methodChannel.setMockMethodCallHandler((call) async { if (call.method == 'previewFile') { return null; // Simulate success } return null; }); // Use the mock await implementation.previewFile('/path/to/file.pdf'); }); } ``` -------------------------------- ### Handle NO_APP_FOUND Error Source: https://github.com/johnny-bytes/native_file_preview/blob/main/_autodocs/errors.md Catch and handle the NO_APP_FOUND error on Android when no installed application can open the specified file type. This prompts the user to install a suitable application. ```dart try { await nativeFilePreview.previewFile('/path/to/file.xyz'); } on PlatformException catch (e) { if (e.code == 'NO_APP_FOUND') { // Handle: No app can open this file type // Show user: "No app available to open this file type" // Suggest: Install a suitable app from Play Store } } ``` -------------------------------- ### Preview File Implementation Source: https://github.com/johnny-bytes/native_file_preview/blob/main/_autodocs/api-reference/NativeFilePreviewPlugin-Android.md Handles the 'previewFile' method call. It takes a map of arguments, expecting a 'file' key with the file path, URL, or content URI. It uses the system Intent to open the file for preview. ```kotlin private fun previewFile(arguments: Map, result: Result) { val filePath = arguments["file"] as? String if (filePath == null) { result.error("INVALID_FILE_PATH", "Missing or null file path", null) return } val activity = activityBinding?.activity if (activity == null) { result.error("NO_ACTIVITY", "No activity available", null) return } try { val uri = Uri.parse(filePath) val intent = Intent(Intent.ACTION_VIEW).apply { setDataAndType(uri, "*/*") addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION) } if (intent.resolveActivity(activity.packageManager) != null) { activity.startActivity(intent) result.success(null) } else { result.error("NO_APP_FOUND", "No app can handle this file type", null) } } catch (e: FileNotFoundException) { result.error("FILE_NOT_FOUND", "File does not exist", e.message) } catch (e: SecurityException) { result.error("CONTENT_URI_INACCESSIBLE", "Content URI cannot be accessed", e.message) } catch (e: Exception) { result.error("INTENT_ERROR", "Intent creation failed", e.message) } } ``` -------------------------------- ### NativeFilePreview Class Definition Source: https://github.com/johnny-bytes/native_file_preview/blob/main/_autodocs/api-reference/NativeFilePreview.md Defines the NativeFilePreview class with methods for getting the platform version and previewing files. ```dart class NativeFilePreview { Future getPlatformVersion() Future previewFile(String filePath) } ``` -------------------------------- ### Show File Preview Source: https://github.com/johnny-bytes/native_file_preview/blob/main/_autodocs/api-reference/NativeFileViewerPreview-iOS.md Creates and presents a file preview modally. Ensure you have a valid UIViewController and handle the completion callback for dismissal. ```swift let fileURL = URL(fileURLWithPath: "/path/to/document.pdf") let preview = NativeFileViewerPreview(file: fileURL) guard let viewController = UIApplication.shared.topViewController() else { return } preview.show(viewController: viewController) { result in // Called when preview is dismissed // result is nil on success } ``` -------------------------------- ### Previewing a File with NativeFilePreview Source: https://github.com/johnny-bytes/native_file_preview/blob/main/_autodocs/OVERVIEW.md Demonstrates how to instantiate and use the NativeFilePreview class to preview a file. Ensure the file path is correctly formatted. ```dart final preview = NativeFilePreview(); await preview.previewFile('/path/to/document.pdf'); ``` -------------------------------- ### Testing MethodChannel previewFile Arguments Source: https://github.com/johnny-bytes/native_file_preview/blob/main/_autodocs/api-reference/MethodChannelNativeFilePreview.md Demonstrates how to test the `previewFile` method by setting up a mock MethodChannel handler to verify that the correct arguments are passed to the native platform. ```dart test('previewFile sends correct arguments', () async { final implementation = MethodChannelNativeFilePreview(); // Set up a mock method channel response implementation.methodChannel.setMockMethodCallHandler((call) async { if (call.method == 'previewFile') { // Verify arguments expect(call.arguments, {'file': '/path/to/file.pdf'}); return null; } }); await implementation.previewFile('/path/to/file.pdf'); }); ``` -------------------------------- ### Get FileProvider URI Source: https://github.com/johnny-bytes/native_file_preview/blob/main/_autodocs/api-reference/NativeFilePreviewPlugin-Android.md Use FileProvider.getUriForFile to obtain a content URI for secure file access on Android 7.0+. ```kotlin val fileProviderUri = FileProvider.getUriForFile( activity, "${activity.packageName}.fileprovider", file ) ``` -------------------------------- ### Basic File Preview Usage Source: https://github.com/johnny-bytes/native_file_preview/blob/main/_autodocs/OVERVIEW.md Import the library, create an instance of NativeFilePreview, and call the previewFile method with the file path. Handle potential PlatformExceptions. ```dart // 1. Import import 'package:native_file_preview/native_file_preview.dart'; // 2. Create instance final _preview = NativeFilePreview(); // 3. Call previewFile try { await _preview.previewFile('/path/to/file.pdf'); } on PlatformException catch (e) { // Handle error print('Error: ${e.code} - ${e.message}'); } ``` -------------------------------- ### previewController(_:previewItemAt:) Source: https://github.com/johnny-bytes/native_file_preview/blob/main/_autodocs/api-reference/NativeFileViewerPreview-iOS.md Implements the `QLPreviewControllerDataSource` protocol to return the preview item at the specified index. This method provides the file URL to be previewed. ```APIDOC ## previewController(_:previewItemAt:) ### Description Returns the preview item at the specified index. This method is part of the `QLPreviewControllerDataSource` protocol and provides the file to be previewed. ### Signature ```swift func previewController(_ controller: QLPreviewController, previewItemAt index: Int) -> QLPreviewItem ``` ### Parameters #### Path Parameters - **controller** (QLPreviewController) - Required - The preview controller requesting the item. - **index** (Int) - Required - The index of the item (always 0 since only 1 item). ### Returns `QLPreviewItem` - The file URL cast as a `QLPreviewItem`. `URL` conforms to the `QLPreviewItem` protocol. ### Details - Returns `self.file` cast as `QLPreviewItem`. - `URL` naturally conforms to `QLPreviewItem` protocol because it can provide a preview representation. - Index parameter is ignored; always returns the single file. ### Implementation ```swift return file as QLPreviewItem ``` ``` -------------------------------- ### NativeFileViewerPreview Constructor Source: https://github.com/johnny-bytes/native_file_preview/blob/main/_autodocs/api-reference/NativeFileViewerPreview-iOS.md Initializes a new NativeFileViewerPreview instance with a specific file URL. This manager is responsible for providing the file to the QuickLook preview controller. ```APIDOC ## init(file:) ### Description Creates a new preview manager for the specified file. This manager will provide the file to the QuickLook preview controller. ### Signature ```swift init(file: URL) ``` ### Parameters #### Path Parameters - **file** (URL) - Required - The file URL to preview. Can be a local file URL or remote HTTP(S) URL. ### Details - Stores the file URL for later use by the preview controller. - The file must be a valid, readable URL by the time `show(viewController:promise:)` is called. ### Example ```swift let fileURL = URL(fileURLWithPath: "/path/to/document.pdf") let preview = NativeFileViewerPreview(file: fileURL) ``` ``` -------------------------------- ### show(viewController:promise:) Source: https://github.com/johnny-bytes/native_file_preview/blob/main/_autodocs/api-reference/NativeFileViewerPreview-iOS.md Creates and presents the preview controller modally. This method is used to initiate the file preview display. ```APIDOC ## show(viewController:promise:) ### Description Creates and presents the preview controller modally. This method is used to initiate the file preview display. ### Method Swift ### Parameters #### Path Parameters - **viewController** (UIViewController) - Yes - The view controller to present the preview from. - **promise** (FlutterResult) - Yes - The Flutter completion callback. Called with `nil` when preview is dismissed. ### Details **Process:** 1. Creates a new `NativeFileViewerPreviewViewController` 2. Sets `self` as the data source for the preview controller 3. Calls `presentModal(viewController:promise:)` to present the preview **Lifecycle:** - The preview controller is presented as a modal - When the user dismisses the preview, the promise is called with `nil` - After dismissal, the preview controller is automatically released ### Example ```swift let fileURL = URL(fileURLWithPath: "/path/to/document.pdf") let preview = NativeFileViewerPreview(file: fileURL) guard let viewController = UIApplication.shared.topViewController() else { return } preview.show(viewController: viewController) { result in // Called when preview is dismissed // result is nil on success } ``` ``` -------------------------------- ### Initialize NativeFileViewerPreview Source: https://github.com/johnny-bytes/native_file_preview/blob/main/_autodocs/api-reference/NativeFileViewerPreview-iOS.md Creates a new preview manager for a specified file. The file must be a valid, readable URL by the time `show(viewController:promise:)` is called. ```swift let fileURL = URL(fileURLWithPath: "/path/to/document.pdf") let preview = NativeFileViewerPreview(file: fileURL) ``` -------------------------------- ### MethodChannelNativeFilePreview Source: https://github.com/johnny-bytes/native_file_preview/blob/main/_autodocs/api-reference/Platform-Interface-Pattern.md The default implementation of the NativeFilePreviewPlatform using MethodChannels to communicate with native code. It exposes methods to get the platform version and preview files. ```APIDOC ## MethodChannelNativeFilePreview ### Description Provides the default implementation for interacting with native file preview features via MethodChannels. This class allows developers to retrieve the platform's version information and trigger file previews. ### Methods #### `getPlatformVersion()` ##### Description Asynchronously retrieves the version of the platform. ##### Returns - `Future`: A future that completes with the platform version string, or null if the version cannot be retrieved. ##### Example ```dart final version = await MethodChannelNativeFilePreview().getPlatformVersion(); print('Platform version: $version'); ``` #### `previewFile(String filePath)` ##### Description Asynchronously triggers the preview of a specified file. ##### Parameters - **filePath** (String) - Required - The absolute path to the file that needs to be previewed. ##### Returns - `Future`: A future that completes when the file preview operation has been initiated. ##### Example ```dart await MethodChannelNativeFilePreview().previewFile('/path/to/your/document.pdf'); ``` ``` -------------------------------- ### previewFile Method Source: https://github.com/johnny-bytes/native_file_preview/blob/main/_autodocs/api-reference/NativeFilePreviewPlatform.md Launches a native file preview for a given file path. This is an abstract method that must be implemented by platform-specific subclasses. ```APIDOC ## Abstract Methods ### previewFile Launches a native file preview for the specified file. #### Signature ```dart Future previewFile(String filePath) ``` #### Parameters | Parameter | Type | Required | Description | |-----------|------|----------|-------------| | filePath | String | Yes | Path to the file to preview. | #### Returns `Future` — A future that completes when the preview action is complete. #### Throws `UnimplementedError` if not overridden by a platform-specific subclass. #### Implementation Notes Platform implementations should handle: - File existence validation - File readability checks - Platform-specific path format conversion - Native UI presentation - Error reporting with specific error codes ``` -------------------------------- ### Implement onAttachedToActivity Source: https://github.com/johnny-bytes/native_file_preview/blob/main/_autodocs/api-reference/NativeFilePreviewPlugin-Android.md Implement this method to get access to the ActivityPluginBinding when an activity is available. This binding is crucial for accessing the application context and launching intents. ```kotlin override fun onAttachedToActivity(binding: ActivityPluginBinding) { activityBinding = binding } ``` -------------------------------- ### Preview File Implementation (Kotlin) Source: https://github.com/johnny-bytes/native_file_preview/blob/main/_autodocs/api-reference/NativeFilePreviewPlugin-Android.md Handles the core logic for previewing a file, including URI resolution, MIME type determination, and launching an intent. It supports content://, file://, and absolute paths, granting necessary read permissions. ```kotlin private fun previewFile(filePath: String, result: Result) ``` -------------------------------- ### Basic File Preview in Flutter Source: https://github.com/johnny-bytes/native_file_preview/blob/main/README.md Demonstrates how to use the NativeFilePreview plugin to preview a file given its path. Includes basic error handling for PlatformExceptions. ```dart import 'package:native_file_preview/native_file_preview.dart'; class FilePreviewExample extends StatelessWidget { final _nativeFilePreview = NativeFilePreview(); Future _previewFile(String filePath) async { try { await _nativeFilePreview.previewFile(filePath); } on PlatformException catch (e) { print('Error previewing file: ${e.message}'); // Handle error (show dialog, snackbar, etc.) } } @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar(title: Text('File Preview Demo')), body: Center( child: ElevatedButton( onPressed: () => _previewFile('/path/to/your/file.pdf'), child: Text('Preview File'), ), ), ); } } ``` -------------------------------- ### previewFile Source: https://github.com/johnny-bytes/native_file_preview/blob/main/_autodocs/OVERVIEW.md Presents a file preview using the native platform's capabilities. On iOS, it displays a QuickLook modal. On Android, it launches an Intent to open the file. ```APIDOC ## previewFile ### Description Presents a file preview using the native platform's capabilities. On iOS, it displays a QuickLook modal. On Android, it launches an Intent to open the file. ### Method Channel `native_file_preview` ### Arguments `Map` - **file** (String) — Path to file ### Return `null` on success ### Errors Platform-specific error codes (e.g., FILE_NOT_FOUND, NO_APP_FOUND) ``` -------------------------------- ### Get Platform Version Abstract Method Source: https://github.com/johnny-bytes/native_file_preview/blob/main/_autodocs/api-reference/NativeFilePreviewPlatform.md Abstract method to be implemented by subclasses to retrieve the platform version string. Returns a future that may resolve to null. ```dart Future getPlatformVersion() ``` -------------------------------- ### Singleton Instance Management Source: https://github.com/johnny-bytes/native_file_preview/blob/main/_autodocs/api-reference/Platform-Interface-Pattern.md Explains how to manage the singleton instance of the NativeFilePreviewPlatform, allowing for default and custom implementations. ```APIDOC ## Singleton Instance Management ### Description Manages a single instance of the `NativeFilePreviewPlatform`. A default instance (`MethodChannelNativeFilePreview`) is provided, and it can be replaced with custom implementations. ### Accessing the Instance - **Getter**: `static NativeFilePreviewPlatform get instance => _instance;` - Retrieves the current singleton instance. ### Setting the Instance - **Setter**: `static set instance(NativeFilePreviewPlatform instance)` - Replaces the current singleton instance with a new one. - Verifies the provided instance using the internal token before assignment. - Example Usage: ```dart NativeFilePreviewPlatform.instance = MyCustomFilePreview(); ``` ``` -------------------------------- ### Return FlutterError for File Not Found in Swift Source: https://github.com/johnny-bytes/native_file_preview/blob/main/_autodocs/types.md Example of returning a `FlutterError` to the Dart layer when a file is not found. This includes a specific error code, message, and optional details. ```swift result(FlutterError(code: "FILE_NOT_FOUND", message: "File does not exist", details: nil)) ``` -------------------------------- ### Create a Mock Native File Preview Implementation Source: https://github.com/johnny-bytes/native_file_preview/blob/main/_autodocs/api-reference/Platform-Interface-Pattern.md Implement a mock version of the NativeFilePreviewPlatform for testing purposes. Set this mock as the active instance to intercept calls. ```dart class MockNativeFilePreview extends NativeFilePreviewPlatform { @override Future getPlatformVersion() async => 'test-version'; @override Future previewFile(String filePath) async { // Custom behavior print('Mock preview: $filePath'); } } // Set as active implementation NativeFilePreviewPlatform.instance = MockNativeFilePreview(); // Now NativeFilePreview uses the mock final preview = NativeFilePreview(); await preview.previewFile('/path/to/file.pdf'); // Uses mock implementation ``` -------------------------------- ### Get File Extension for MIME Type Source: https://github.com/johnny-bytes/native_file_preview/blob/main/_autodocs/types.md Determine the MIME type of a file based on its extension. This function maps common file extensions to their corresponding MIME types. ```kotlin private fun getMimeTypeFromFile(file: File): String? { val extension = file.extension.lowercase() return when (extension) { "pdf" -> "application/pdf" else -> null } } ``` -------------------------------- ### Get Platform Version using MethodChannelNativeFilePreview Source: https://github.com/johnny-bytes/native_file_preview/blob/main/_autodocs/api-reference/MethodChannelNativeFilePreview.md Retrieve the platform version string from the native code. This method returns a Future that resolves to the version string or null if unavailable. ```dart final implementation = MethodChannelNativeFilePreview(); final version = await implementation.getPlatformVersion(); print('Platform version: $version'); ``` -------------------------------- ### Mocking MethodChannelNativeFilePreview for Testing Source: https://github.com/johnny-bytes/native_file_preview/blob/main/_autodocs/api-reference/MethodChannelNativeFilePreview.md Demonstrates how to mock the MethodChannelNativeFilePreview to test its methods, specifically previewFile and getPlatformVersion. This is useful for unit testing platform channel interactions without needing a real device or emulator. ```dart import 'package:flutter_test/flutter_test.dart'; import 'package:native_file_preview/native_file_preview_method_channel.dart'; void main() { test('MethodChannelNativeFilePreview.previewFile', () async { final implementation = MethodChannelNativeFilePreview(); // Mock the method channel implementation.methodChannel.setMockMethodCallHandler((call) async { if (call.method == 'previewFile') { return null; } return null; }); // Should not throw await implementation.previewFile('/path/to/file.pdf'); }); test('MethodChannelNativeFilePreview.getPlatformVersion', () async { final implementation = MethodChannelNativeFilePreview(); implementation.methodChannel.setMockMethodCallHandler((call) async { if (call.method == 'getPlatformVersion') { return '1.0.0'; } return null; }); final version = await implementation.getPlatformVersion(); expect(version, '1.0.0'); }); } ``` -------------------------------- ### Preview a File with NativeFilePreview Source: https://github.com/johnny-bytes/native_file_preview/blob/main/example/README.md Instantiate NativeFilePreview and call the previewFile method with the desired file path. Ensure the file exists and is accessible. ```dart final nativeFilePreview = NativeFilePreview(); await nativeFilePreview.previewFile('/path/to/file.txt'); ``` -------------------------------- ### previewFile Source: https://github.com/johnny-bytes/native_file_preview/blob/main/_autodocs/api-reference/MethodChannelNativeFilePreview.md Sends a request to the native platform to preview a file. This method takes a file path as input and initiates the native file preview mechanism. ```APIDOC ## previewFile ### Description Sends a request to the native platform to preview a file. Supports absolute paths, file:// URLs, and content:// URIs. ### Method MethodChannel ### Endpoint previewFile ### Parameters #### Arguments - **filePath** (String) - Yes - Path to the file to preview. Supports absolute paths, file:// URLs, and content:// URIs. ### Method Channel Details - **Method name:** `'previewFile'` - **Arguments:** `{'file': filePath}` (Map) - **Return type:** `void` (returns null) ### Error Handling Platform exceptions are raised with error codes defined by the native implementation: | Error Code | |------------| | `INVALID_ARGUMENTS` | | `FILE_NOT_FOUND` | | `FILE_NOT_READABLE` | | `NO_VIEW_CONTROLLER` | | `NO_ACTIVITY` | | `NO_APP_FOUND` | | `CONTENT_URI_INACCESSIBLE` | ### Example ```dart import 'package:native_file_preview/native_file_preview_method_channel.dart'; final channel = MethodChannelNativeFilePreview(); try { await channel.previewFile('/path/to/document.pdf'); } on PlatformException catch (e) { print('Error: ${e.code} - ${e.message}'); } ``` ``` -------------------------------- ### previewFile Source: https://github.com/johnny-bytes/native_file_preview/blob/main/_autodocs/api-reference/NativeFilePreviewPlugin-iOS.md Opens a file preview for the specified file. It takes a map containing the file path as an argument and returns nil on success. Errors can occur if arguments are invalid, the file URL is invalid, the file is not found or readable, or if no view controller is available. ```APIDOC ## previewFile ### Description Opens a file preview for the specified file. This method is used to display the content of a file to the user. ### Method `previewFile` ### Arguments - `file` (String) - Required - The path to the file to be previewed. ### Return `nil` on success. ### Errors - `INVALID_ARGUMENTS`: Indicates that the provided arguments are not valid. - `INVALID_FILE_URL`: Indicates that the file URL is invalid. - `FILE_NOT_FOUND`: Indicates that the specified file could not be found. - `FILE_NOT_READABLE`: Indicates that the file is not readable. - `NO_VIEW_CONTROLLER`: Indicates that no view controller is available to display the preview. ``` -------------------------------- ### previewFile Source: https://github.com/johnny-bytes/native_file_preview/blob/main/README.md Opens the specified file using the platform's native preview functionality. This method handles the underlying platform-specific implementations for displaying file previews. ```APIDOC ## previewFile(String filePath) ### Description Opens the specified file using the platform's native preview functionality. ### Method `previewFile` ### Parameters #### Path Parameters - **filePath** (String) - Required - Path to the file to preview. Supports local paths, file:// URLs, and content:// URIs. ### Returns `Future` ### Throws `PlatformException` with specific error codes for different failure scenarios. ``` -------------------------------- ### Return Single Preview Item Source: https://github.com/johnny-bytes/native_file_preview/blob/main/_autodocs/api-reference/NativeFileViewerPreview-iOS.md Returns the single file URL as a QLPreviewItem. The index parameter is ignored as this class only handles one file. ```swift return file as QLPreviewItem ``` -------------------------------- ### Preview File Abstract Method Source: https://github.com/johnny-bytes/native_file_preview/blob/main/_autodocs/api-reference/NativeFilePreviewPlatform.md Abstract method that must be implemented by subclasses to launch a native file preview. Requires the file path as input. ```dart Future previewFile(String filePath) ``` -------------------------------- ### Configure File Paths in res/xml/file_paths.xml Source: https://github.com/johnny-bytes/native_file_preview/blob/main/_autodocs/configuration.md Define accessible directories for FileProvider by creating this XML file. Use elements like , , etc., to specify access scopes. ```xml ``` -------------------------------- ### presentModal Source: https://github.com/johnny-bytes/native_file_preview/blob/main/_autodocs/api-reference/NativeFileViewerPreviewViewController-iOS.md Presents the preview controller modally and stores the completion callback. This method is used to display the file preview to the user and ensures that a callback is triggered upon dismissal. ```APIDOC ## presentModal(viewController:promise:) ### Description Presents the preview controller modally and stores the completion callback. This method is used to display the file preview to the user and ensures that a callback is triggered upon dismissal. ### Method Swift ### Parameters #### Path Parameters - **viewController** (UIViewController) - Required - The view controller from which to present the preview. - **promise** (FlutterResult) - Required - The callback to invoke when preview is dismissed. ### Request Example ```swift let previewController = NativeFileViewerPreviewViewController() previewController.dataSource = someDataSource previewController.presentModal(viewController: self) { result in print("Preview dismissed") // result is nil } ``` ### Details 1. Stores the `promise` callback in the instance variable. 2. Calls `viewController.present(self, animated: true)` to present the preview controller modally. 3. The presentation is animated (slides up from bottom on iOS). **Timing:** - `promise` is stored before presentation. - Presentation occurs with animation. - User can interact with the preview. - When user dismisses preview, `viewWillDisappear` is called. - `promise` callback is invoked with `nil`. ``` -------------------------------- ### Complete Error Handling Pattern for File Preview Source: https://github.com/johnny-bytes/native_file_preview/blob/main/_autodocs/errors.md This pattern demonstrates comprehensive error handling for the `previewFile` method. It catches `PlatformException` to manage specific file-related errors and includes a general catch block for unexpected issues. Use this to provide user-friendly feedback for various failure scenarios. ```dart import 'package:flutter/services.dart'; Future previewFileWithErrorHandling(String filePath) async { try { await nativeFilePreview.previewFile(filePath); } on PlatformException catch (e) { switch (e.code) { case 'FILE_NOT_FOUND': _showError('File not found', 'The file does not exist'); break; case 'FILE_NOT_READABLE': _showError('Permission denied', 'Cannot access this file'); break; case 'NO_APP_FOUND': _showError('No app available', 'Install an app to view this file type'); break; case 'NO_VIEW_CONTROLLER': case 'NO_ACTIVITY': _showError('Try again', 'The app is not ready. Please try again.'); break; case 'CONTENT_URI_INACCESSIBLE': _showError('Invalid file', 'Cannot access this file'); break; default: _showError('Preview failed', e.message ?? 'Unknown error'); } } catch (e) { _showError('Unexpected error', e.toString()); } } void _showError(String title, String message) { // Show error to user (dialog, snackbar, etc.) } ``` -------------------------------- ### Singleton Instance Management for Platform Interface Source: https://github.com/johnny-bytes/native_file_preview/blob/main/_autodocs/api-reference/Platform-Interface-Pattern.md Details how to manage a singleton instance of the platform interface, including its default implementation and how to set a custom one. ```dart static NativeFilePreviewPlatform _instance = MethodChannelNativeFilePreview(); static NativeFilePreviewPlatform get instance => _instance; static set instance(NativeFilePreviewPlatform instance) { PlatformInterface.verifyToken(instance, _token); _instance = instance; } ``` -------------------------------- ### Preview a File Source: https://github.com/johnny-bytes/native_file_preview/blob/main/_autodocs/README.md Instantiate the NativeFilePreview class and call the previewFile method with the absolute path to the file you want to preview. Ensure the file path is correctly formatted. ```dart import 'package:native_file_preview/native_file_preview.dart'; final preview = NativeFilePreview(); await preview.previewFile('/path/to/file.pdf'); ``` -------------------------------- ### NativeFilePreviewPlatform Instance Source: https://github.com/johnny-bytes/native_file_preview/blob/main/_autodocs/api-reference/NativeFilePreviewPlatform.md Access and set the default or custom platform implementation for native file preview. ```APIDOC ## Static Members ### instance (getter) Retrieves the default platform implementation instance. #### Signature ```dart static NativeFilePreviewPlatform get instance => _instance ``` #### Returns `NativeFilePreviewPlatform` — The current platform implementation, which defaults to `MethodChannelNativeFilePreview`. #### Example ```dart // Get the current platform instance final platform = NativeFilePreviewPlatform.instance; final version = await platform.getPlatformVersion(); ``` --- ### instance (setter) Replaces the default platform implementation with a custom one. #### Signature ```dart static set instance(NativeFilePreviewPlatform instance) ``` #### Parameters | Parameter | Type | Required | Description | |-----------|------|----------|-------------| | instance | NativeFilePreviewPlatform | Yes | A subclass implementing the platform interface. Must pass token verification. | #### Throws `AssertionError` if the instance does not have the correct token, indicating an unauthorized implementation. #### Example ```dart // Replace with a mock implementation for testing class MockNativeFilePreview extends NativeFilePreviewPlatform { @override Future getPlatformVersion() async => '1.0.0'; @override Future previewFile(String filePath) async {} } // Set the mock as the active instance NativeFilePreviewPlatform.instance = MockNativeFilePreview(); ``` ``` -------------------------------- ### Initialize NativeFileViewerPreview with URL in Swift Source: https://github.com/johnny-bytes/native_file_preview/blob/main/_autodocs/types.md Demonstrates initializing the `NativeFileViewerPreview` class with a `URL` object. This class is designed to hold a file URL for previewing. ```swift class NativeFileViewerPreview { private let file: URL init(file: URL) { self.file = file } } ``` -------------------------------- ### Preview Local File using path_provider Source: https://github.com/johnny-bytes/native_file_preview/blob/main/README.md Preview a local file by obtaining its path using the `path_provider` package. This is useful for accessing app-specific directories. ```dart // Using path_provider final directory = await getApplicationDocumentsDirectory(); await nativeFilePreview.previewFile('${directory.path}/my_file.txt'); ``` -------------------------------- ### previewFile Source: https://github.com/johnny-bytes/native_file_preview/blob/main/_autodocs/api-reference/NativeFilePreview.md Opens the specified file using the platform's native preview functionality. This method supports various file path formats including absolute paths, file:// URLs, and content:// URIs on Android. ```APIDOC ## previewFile ### Description Opens the specified file using the platform's native preview functionality. Supports absolute paths, `file://` URLs, and `content://` URIs (Android). ### Method `Future previewFile(String filePath)` ### Parameters #### Path Parameters - **filePath** (String) - Required - Path to the file to preview. Supports absolute paths, `file://` URLs, and `content://` URIs (Android). ### Returns `Future` — Completes when the file preview is launched. The future completes with null on success when the preview controller is dismissed (iOS) or the intent is handled (Android). ### Error Handling Throws `PlatformException` with one of the following error codes: | Error Code | |---| | `INVALID_ARGUMENTS` | | `FILE_NOT_FOUND` | | `FILE_NOT_READABLE` | | `INVALID_FILE_URL` | | `NO_VIEW_CONTROLLER` | | `NO_ACTIVITY` | | `NO_APP_FOUND` | | `CONTENT_URI_INACCESSIBLE` | ### Example ```dart import 'package:native_file_preview/native_file_preview.dart'; class FilePreviewScreen extends StatefulWidget { @override _FilePreviewScreenState createState() => _FilePreviewScreenState(); } class _FilePreviewScreenState extends State { final _nativeFilePreview = NativeFilePreview(); void _previewFile() async { try { // Preview a local file await _nativeFilePreview.previewFile('/path/to/document.pdf'); } on PlatformException catch (e) { _showErrorDialog('Preview Error', e.code, e.message); } } void _showErrorDialog(String title, String code, String? message) { showDialog( context: context, builder: (context) => AlertDialog( title: Text(title), content: Text('Error: $code\n${message ?? "Unknown error"}'), actions: [ TextButton( onPressed: () => Navigator.pop(context), child: Text('OK'), ), ], ), ); } @override Widget build(BuildContext context) { return ElevatedButton( onPressed: _previewFile, child: Text('Preview PDF'), ); } } ``` ### Platform-Specific Behavior **iOS:** Uses the QuickLook framework to display a native preview controller. The preview controller is presented modally and can be dismissed by the user. When dismissed, the future completes. **Android:** Uses the Intent system with `ACTION_VIEW` to launch an app capable of viewing the file. The method returns immediately after the intent is issued, without waiting for the app to be dismissed. ### File Path Format Support The method accepts multiple file path formats: - **Absolute paths:** `/storage/emulated/0/Download/document.pdf` - **File URLs:** `file:///storage/emulated/0/Download/image.jpg` - **Content URIs (Android only):** `content://com.android.providers.downloads.documents/document/123` ``` -------------------------------- ### Flutter Build Commands Source: https://github.com/johnny-bytes/native_file_preview/blob/main/_autodocs/configuration.md Standard Flutter commands for building the application for different platforms. No special configuration is needed for the plugin itself. ```bash flutter build ios ``` ```bash flutter build apk ``` ```bash flutter build appbundle ``` -------------------------------- ### Handle previewFile Method Call on iOS Source: https://github.com/johnny-bytes/native_file_preview/blob/main/_autodocs/api-reference/Platform-Interface-Pattern.md Implement the method channel handler for the 'previewFile' method on iOS. This code processes the file path argument and can return success or an error. ```swift // NativeFilePreviewPlugin.swift class NativeFilePreviewPlugin: NSObject, FlutterPlugin { func handle(_ call: FlutterMethodCall, result: @escaping FlutterResult) { switch call.method { case "previewFile": // Handle preview request let filePath = call.arguments as? String // ... implementation result(nil) // or result(FlutterError(...)) default: result(FlutterMethodNotImplemented) } } } ``` -------------------------------- ### Handle previewFile Method Call on Android Source: https://github.com/johnny-bytes/native_file_preview/blob/main/_autodocs/api-reference/Platform-Interface-Pattern.md Implement the method channel handler for the 'previewFile' method on Android. This code extracts the file path from the arguments and can return success or an error. ```kotlin // NativeFilePreviewPlugin.kt class NativeFilePreviewPlugin: FlutterPlugin, MethodCallHandler { override fun onMethodCall(call: MethodCall, result: Result) { when (call.method) { "previewFile" -> { val filePath = (call.arguments as? Map<*, *>)?.get("file") as? String // ... implementation result.success(null) // or result.error(...) } else -> result.notImplemented() } } } ``` -------------------------------- ### Import NativeFilePreview API Source: https://github.com/johnny-bytes/native_file_preview/blob/main/_autodocs/OVERVIEW.md Import the main NativeFilePreview API class from the package. This is the primary entry point for using the library's functionality. ```dart import 'package:native_file_preview/native_file_preview.dart'; ``` -------------------------------- ### Check File Existence Source: https://github.com/johnny-bytes/native_file_preview/blob/main/_autodocs/types.md Instantiate a File object with a file path and use the exists() method to check if the file is present on the filesystem. Return an error if the file does not exist. ```kotlin class File(pathname: String) { fun exists(): Boolean val extension: String val path: String } ``` ```kotlin val file = File(filePath) if (!file.exists()) { result.error("FILE_NOT_FOUND", "File does not exist: $filePath", null) return } ```