# Magic Picker documentation > Magic Picker lets a Magic app pick a file, an image or a video and get a MagicFile back through the Pick facade. # Installation Add `magic_picker` to a Magic app, register its provider and check that `Pick` opens a picker. - [Install](#install) - [Requirements](#requirements) - [Register the Provider](#register-the-provider) - [Verify](#verify) - [Related Documentation](#related-documentation) ## Install ```bash flutter pub add magic_picker dart run magic:dowel plugin:install magic_picker ``` The installer reads the package's `install.yaml` and injects `PickerServiceProvider` into the `providers` list of `lib/config/app.dart`. It publishes no config file and adds no config factory: `Pick` needs no settings. ```dart import 'package:magic_picker/magic_picker.dart'; ``` The barrel is the only import; everything under `src/` is private. It also re-exports `XFile` and `CameraDevice` from `image_picker`, because both appear in this package's signatures. ## Requirements | Requirement | Value | |:------------|:------| | Dart | `>=3.13.0` | | Flutter | `>=3.47.0` | | Magic | `^1.0.0`, installed and bootstrapped (`lib/config/app.dart` exists) | | Dependencies | `dowel`, `file_picker`, `image_picker` and `share_plus`, pulled in automatically | ## Register the Provider `plugin:install` does this for you. To do it by hand, add the provider to `lib/config/app.dart`: ```dart import 'package:magic_picker/magic_picker.dart'; final Map appConfig = { 'app': { 'providers': [ (app) => PickerServiceProvider(app), ], }, }; ``` `Pick` itself is a static facade and works without the provider. The provider has one job: in `boot()` it sets `LocalAdapterContract.downloadHandler`, so `Storage.download` can open the share sheet on mobile, macOS and Windows, and the save dialog on Linux, where `share_plus` cannot share a file. Without it that call throws on mobile and desktop, see [Download](https://anilcancakir.com/magic/docs/picker/basics/download.md). ## Verify ```dart import 'package:magic_picker/magic_picker.dart'; Future main() async { final image = await Pick.image(); print(image?.name ?? 'cancelled'); } ``` Run it on a device or in a browser. The system gallery opens; choosing an image prints its file name, and dismissing it prints `cancelled`. The result is a `MagicFile`, a type that lives in `package:magic/magic.dart`; import it when you name it. ## Related Documentation - [Pick](https://anilcancakir.com/magic/docs/picker/basics/pick.md): every picker and what it returns. - [XFile Conversion](https://anilcancakir.com/magic/docs/picker/basics/xfile.md): `toMagicFile` and `toXFile`. - [Download](https://anilcancakir.com/magic/docs/picker/basics/download.md): the share-sheet download handler. - [Testing](https://anilcancakir.com/magic/docs/picker/guides/testing.md): testing code that calls `Pick` or `Storage.download`. --- # Pick Open the system gallery, camera, file dialog and save dialog through the `Pick` facade and get a `MagicFile` back on every platform. - [Basic Usage](#basic-usage) - [Quick Reference](#quick-reference) - [Images](#images) - [Camera](#camera) - [Video](#video) - [Files](#files) - [Saving a File](#saving-a-file) - [Working with the Result](#working-with-the-result) - [Platform Support](#platform-support) - [Gotchas](#gotchas) - [Related Documentation](#related-documentation) ## Basic Usage ```dart import 'package:magic_picker/magic_picker.dart'; Future main() async { final image = await Pick.image(maxWidth: 1024, imageQuality: 85); if (image == null) return; // The user cancelled. print('${image.name}: ${image.size} bytes'); await image.store('avatars/profile.jpg'); } ``` `Pick` is a static facade over `image_picker` and `file_picker`. Every picker that returns a file answers with a `MagicFile` from core, or `null` (a list: empty) when the user cancels, so a cancelled pick is never an error. ## Quick Reference | Member | Returns | Meaning | |:-------|:--------|:--------| | `Pick.image({maxWidth, maxHeight, imageQuality})` | `Future` | One image from the gallery. `imageQuality` is 0 to 100. | | `Pick.images({maxWidth, maxHeight, imageQuality})` | `Future>` | Several images from the gallery. | | `Pick.camera({preferredCamera, maxWidth, maxHeight, imageQuality, fallbackToGallery, onError})` | `Future` | A photo from the camera. | | `Pick.media({maxWidth, maxHeight, imageQuality})` | `Future` | One image or one video from the gallery. | | `Pick.video({maxDuration})` | `Future` | One video from the gallery. | | `Pick.recordVideo({preferredCamera, maxDuration, fallbackToGallery, onError})` | `Future` | A video recorded with the camera. | | `Pick.file({extensions})` | `Future` | One file of any type, or of the listed extensions. | | `Pick.files({extensions})` | `Future>` | Several files. | | `Pick.directory()` | `Future` | A directory path. Not supported on the web. | | `Pick.saveFile({fileName, bytes, mimeType, dialogTitle})` | `Future` | Writes `bytes` through the save dialog and answers where they went. | ## Images ```dart import 'package:magic_picker/magic_picker.dart'; Future main() async { final image = await Pick.image(maxWidth: 800, maxHeight: 800); final gallery = await Pick.images(imageQuality: 80); print(image?.name); print(gallery.length); // 0 when the user cancels } ``` `maxWidth` and `maxHeight` are pixel limits that shrink the picked image; leave them unset to keep the original. `imageQuality` is a number from 0 to 100. ## Camera ```dart import 'package:magic_picker/magic_picker.dart'; Future main() async { final photo = await Pick.camera( preferredCamera: CameraDevice.front, fallbackToGallery: true, onError: (Object error) => print('Camera failed: $error'), ); print(photo?.name); } ``` `CameraDevice` is re-exported from this package, so no extra import is needed. When the camera fails, for example because the permission was refused, the outcome depends on two arguments: | `onError` | `fallbackToGallery` | What happens on failure | |:----------|:--------------------|:------------------------| | unset | `false` | The error is rethrown. | | set | `false` | `onError` runs and the call answers `null`. | | either | `true` | `onError` runs when set, then the gallery picker opens. | With `fallbackToGallery: true` the gallery also opens when the user closes the camera without a photo. `Pick.recordVideo` takes the same two arguments and falls back to `Pick.video`. ## Video ```dart import 'package:magic_picker/magic_picker.dart'; Future main() async { final clip = await Pick.video(maxDuration: const Duration(seconds: 30)); final recording = await Pick.recordVideo( preferredCamera: CameraDevice.rear, maxDuration: const Duration(minutes: 1), ); print(clip?.isVideo); // true print(recording?.name); } ``` ## Files ```dart import 'package:magic_picker/magic_picker.dart'; Future main() async { final anyFile = await Pick.file(); final pdf = await Pick.file(extensions: ['pdf']); final documents = await Pick.files(extensions: ['pdf', 'doc', 'docx']); final directory = await Pick.directory(); print([anyFile?.name, pdf?.name, documents.length, directory]); } ``` `extensions` are written without the dot. Passing the list restricts the dialog to those types; leaving it out allows any file. File contents are not read at pick time: bytes load on demand through `readAsBytes`, so a large selection costs nothing until you store or upload it. ## Saving a File ```dart import 'dart:typed_data'; import 'package:magic_picker/magic_picker.dart'; Future save(Uint8List pdfBytes) async { final savedTo = await Pick.saveFile( fileName: 'report.pdf', bytes: pdfBytes, ); if (savedTo != null && savedTo.scheme == 'file') { print(savedTo.toFilePath()); } } ``` `saveFile` opens the platform save dialog, writes the bytes and answers the `Uri` it wrote to, or `null` when the user cancels. The web has no dialog here: the browser downloads the file. The scheme depends on the platform: | Platform | Scheme | |:---------|:-------| | Desktop and iOS | `file` | | Android | None: the answer is the path part of the Storage Access Framework document uri, not a path you can open | | Web | None: the answer is always `null`, because the browser reports no location | Call `toFilePath()` only after checking for `file`. The MIME type comes from the extension of `fileName` (`report.pdf` becomes `application/pdf`) and falls back to `application/octet-stream`. Pass `mimeType` when the extension does not describe the content: Android and the browser both use it to choose the app that opens the file. ## Working with the Result `MagicFile` is core's class; these are the members used most after a pick. | Member | Meaning | |:-------|:--------| | `name`, `extension`, `mimeType` | The file name, its extension without the dot, and a MIME type: the one the picker reports, else one derived from the name (`null` when the extension is unknown). | | `size` | Bytes, filled for every pick. Treat `null` and `0` as unknown when you enforce an upload limit. | | `path` | The file path when the platform gives one, `null` otherwise; mobile and desktop picks give one. On the web an image, video or media pick answers a `blob:` URL; a `Pick.file` or `Pick.files` pick answers `null`. | | `isImage`, `isVideo` | Derived from the extension. | | `readAsBytes()` | The bytes, read once and cached. | | `store(path, {disk})`, `storeAs(directory, {disk})` | Write to `Storage`; `storeAs` generates a unique name. | | `upload(url, {fieldName, data, headers})` | Send as multipart form data through `Http`. | ```dart import 'package:magic_picker/magic_picker.dart'; Future uploadAvatar() async { final image = await Pick.image(maxWidth: 512, imageQuality: 80); if (image == null) return; final response = await image.upload('/api/user/avatar', fieldName: 'avatar'); print(response.successful); } ``` ## Platform Support | Method | Android | iOS | Web | Desktop | |:-------|:--------|:----|:----|:--------| | `image`, `images`, `media`, `video` | yes | yes | yes | yes | | `camera`, `recordVideo` | yes | yes | yes | needs a custom `image_picker` camera delegate | | `file`, `files`, `saveFile` | yes | yes | yes | yes | | `directory` | yes | yes | no | yes | Each platform's permission setup (photo library and camera usage descriptions on iOS and macOS, file-access entitlements on macOS) is the app's responsibility. ## Gotchas | Mistake | Fix | |:--------|:----| | Treating `null` as a failure | `null` is a cancelled pick. Return early. | | Calling `Pick.camera` with no `onError` and no fallback | A refused permission rethrows. Pass one of the two. | | Reading `path` on the web | It is a `blob:` URL for an image pick and `null` for a `Pick.file` pick, and neither is a file path; use `readAsBytes` or `store`. | | Trusting `size` as a limit | It can be `null` or `0` when the file vanished after the pick. Check the stored size too. | | Calling `savedTo.toFilePath()` without checking the scheme | Only a `file` uri is a path you can open; the Android answer has no scheme, so it converts to a string that is not a real file path, and the web answers `null`. | | Passing `withData` to `Pick.file` or `Pick.files` | The parameter no longer exists. Read bytes with `readAsBytes`. | | Calling `Pick.directory` on the web | It is not supported there. | ## Related Documentation - [XFile Conversion](https://anilcancakir.com/magic/docs/picker/basics/xfile.md): handing a picked file to code that speaks `XFile`. - [Download](https://anilcancakir.com/magic/docs/picker/basics/download.md): sharing a stored file with `Storage.download`. - [Testing](https://anilcancakir.com/magic/docs/picker/guides/testing.md): testing code that calls `Pick`. --- # Download Offer a stored file to the user with `Storage.download`: the share sheet on mobile, macOS and Windows, the save dialog on Linux, a browser download on the web. - [Basic Usage](#basic-usage) - [Quick Reference](#quick-reference) - [How the Handler Works](#how-the-handler-works) - [Without the Plugin](#without-the-plugin) - [Gotchas](#gotchas) - [Related Documentation](#related-documentation) ## Basic Usage ```dart import 'package:magic/magic.dart'; Future main() async { await Storage.download('reports/2024.pdf', name: 'Annual Report.pdf'); } ``` `Storage` is core's facade. `magic_picker` supplies the part core cannot ship, the share sheet, by registering `PickerServiceProvider`. Register it once in `lib/config/app.dart` (the installer does) and the call above works on every platform. ## Quick Reference | Platform | What `Storage.download` does | |:---------|:-----------------------------| | Android, iOS, macOS and Windows | Calls `LocalAdapterContract.downloadHandler`, which `PickerServiceProvider` sets to open the share sheet. | | Linux | The same handler opens the save dialog with the file's bytes, because `share_plus` cannot share a file there. Closing the dialog ends the call without an error. | | Web | Triggers a browser download. The handler is never called. | The `name` argument is the file name offered to the user. Without it the file's own base name is used. ## How the Handler Works `LocalAdapterContract.downloadHandler` is a static `Future Function(String fullPath, String name)?` in core. `PickerServiceProvider.boot()` assigns it, so the share sheet is wired after `Magic.init` has booted the providers. The handler shares the stored file through `share_plus` and passes `name` as the file name override, because `XFile` ignores its `name` on IO and would otherwise offer the path's base name. On Linux `share_plus` throws `UnimplementedError` for any file, so the handler reads the file and passes `name` and the bytes to `Pick.saveFile`, which opens the save dialog. On Windows older than 10 version 1809 (build 17763), `share_plus` falls back to an implementation that throws `UnimplementedError` for any file, so `download` throws there. The provider does not detect it. `PickerServiceProvider` takes an optional `share` callback that replaces the share sheet. It exists for tests, where there is no platform channel to answer; see [Testing](https://anilcancakir.com/magic/docs/picker/guides/testing.md). ## Without the Plugin On mobile and desktop `download` throws `UnsupportedError` while no handler is set. The message names `magic_picker`: ```text Storage download on IO platforms needs a handler. Install magic_picker or set LocalAdapterContract.downloadHandler. ``` Install the plugin, or assign your own handler, for example one that copies the file to a folder you choose. A file that does not exist makes `download` throw an `Exception` before the handler is reached. ## Gotchas | Mistake | Fix | |:--------|:----| | Calling `Storage.download` on mobile or desktop without the plugin | Register `PickerServiceProvider`, or set `LocalAdapterContract.downloadHandler` yourself. | | Expecting a share sheet on Linux | There is none: the user gets a save dialog and picks where the file goes. | | Expecting the handler to run on the web | The web adapter downloads through the browser and ignores it. | | Assigning your own handler before `Magic.init` finishes | `PickerServiceProvider.boot()` runs during init and overwrites it. Assign yours after boot. | | Downloading a path that was never stored | `download` throws an `Exception` saying the file was not found. | ## Related Documentation - [Pick](https://anilcancakir.com/magic/docs/picker/basics/pick.md): picking the file that you later store. - [XFile Conversion](https://anilcancakir.com/magic/docs/picker/basics/xfile.md): the `XFile` the share sheet receives. - [Testing](https://anilcancakir.com/magic/docs/picker/guides/testing.md): recording share calls and resetting the handler. --- # XFile Conversion Move between `MagicFile` and `XFile` with the `toMagicFile` and `toXFile` extensions. - [Basic Usage](#basic-usage) - [Quick Reference](#quick-reference) - [IO Versus Web](#io-versus-web) - [Gotchas](#gotchas) - [Related Documentation](#related-documentation) ## Basic Usage ```dart import 'package:magic/magic.dart'; import 'package:magic_picker/magic_picker.dart'; Future roundTrip(XFile picked) async { final MagicFile file = await picked.toMagicFile(); print('${file.name}: ${file.size} bytes'); final xFile = await Future.value(file.toXFile()); print(xFile.name); } ``` The `Future.value` wrapper is what makes the sample compile on both platforms: `toXFile` is synchronous on mobile and desktop and returns a `Future` on the web. `XFile` is re-exported from this package, so `package:magic_picker/magic_picker.dart` is the only import you need for it. ## Quick Reference | Member | Returns | Meaning | |:-------|:--------|:--------| | `XFile.toMagicFile()` | `Future` | Builds a `MagicFile` from the `XFile`'s path, name, MIME type and length. Bytes load on demand. | | `MagicFile.toXFile()` on IO | `XFile` | Wraps `path` without reading the file. Throws `UnsupportedError` when `path` is `null`. | | `MagicFile.toXFile()` on the web | `Future` | Reads the bytes and builds an in-memory `XFile`. Throws `UnsupportedError` when there are no bytes. | `toMagicFile` is the same everywhere. It reads `XFile.length`, so `size` is filled without reading the content; on the web that is the blob's size. ## IO Versus Web The package picks the `toXFile` implementation at compile time: the web build gets the `Future`, every other build gets the synchronous one. Code that only ever targets mobile and desktop can call it without `await`. Code that also runs on the web has to treat the result as possibly asynchronous, as the `Future.value` wrapper above does, or branch on `kIsWeb` and write each call on its own. A `MagicFile` built from bytes alone, such as a generated report, has no `path`, so `toXFile` throws on IO. Store the file first and convert from the stored path, or build the `XFile` yourself with `XFile.fromData`. ## Gotchas | Mistake | Fix | |:--------|:----| | Calling `file.toXFile().path` on code that also builds for the web | There it is a `Future`. `await` the result, or wrap it in `Future.value`. | | Converting a bytes-only `MagicFile` on mobile | It has no `path` and throws `UnsupportedError`. Convert a stored or picked file instead. | | Expecting `toMagicFile` to read the file | It only reads the length. Call `readAsBytes` when you need the content. | ## Related Documentation - [Pick](https://anilcancakir.com/magic/docs/picker/basics/pick.md): the pickers that already return `MagicFile`. - [Download](https://anilcancakir.com/magic/docs/picker/basics/download.md): `Storage.download` shares through an `XFile`. --- # Testing Test code that calls `Pick`, `Storage.download` and the `XFile` conversions without a device, a share sheet or a mocking library. - [The Download Handler](#the-download-handler) - [Resetting the Static](#resetting-the-static) - [Faking the Pickers](#faking-the-pickers) - [Converting Files](#converting-files) - [Related Documentation](#related-documentation) ## The Download Handler `PickerServiceProvider` takes a `share` callback in place of the platform share sheet, which a test cannot reach without a platform channel. Boot the provider by hand and record what it is asked to share: ```dart import 'package:flutter_test/flutter_test.dart'; import 'package:magic/magic.dart'; import 'package:magic_picker/magic_picker.dart'; import 'package:share_plus/share_plus.dart'; void main() { late List shared; setUp(() { MagicApp.reset(); Magic.flush(); shared = []; }); tearDown(() { LocalAdapterContract.downloadHandler = null; }); test('boot installs the download handler', () async { expect(LocalAdapterContract.downloadHandler, isNull); await PickerServiceProvider( Magic.app, share: (ShareParams params) async => shared.add(params), ).boot(); await LocalAdapterContract.downloadHandler!('/tmp/a.txt', 'report.txt'); expect(shared.single.fileNameOverrides, ['report.txt']); }); } ``` `share_plus` is a dependency of this package, so add it to your own `dev_dependencies` when a test names `ShareParams`. To go through `Storage.download`, boot Magic with the provider in `'app': {'providers': [...]}`; `Magic.init` reads `path_provider`, so mock its channel in `setUpAll`. ## Resetting the Static `LocalAdapterContract.downloadHandler` is a static field. `MagicApp.reset()` and `Magic.flush()` do not clear it, so a handler installed by one test is still there in the next. Set it back to `null` in `tearDown`, as the sample above does. ## Faking the Pickers `Pick` calls the platform singletons that `image_picker` and `file_picker` publish: `ImagePickerPlatform.instance` for images, camera and video, and `FilePickerPlatform.instance` for files, directories and the save dialog. A test replaces the instance with a fake that extends the platform interface and restores the original afterwards. Depend on `image_picker_platform_interface` and `file_picker` in `dev_dependencies` to name them. The package's own `test/facades/pick_test.dart` shows complete fakes of both. ## Converting Files The conversions need no fake. Build a `MagicFile` by hand and convert it: ```dart import 'package:flutter_test/flutter_test.dart'; import 'package:magic/magic.dart'; import 'package:magic_picker/magic_picker.dart'; void main() { setUp(() { MagicApp.reset(); Magic.flush(); }); test('a MagicFile with a path wraps into an XFile', () { final file = MagicFile( path: '/tmp/photo.jpg', name: 'photo.jpg', mimeType: 'image/jpeg', ); final XFile xFile = file.toXFile(); expect(xFile.path, '/tmp/photo.jpg'); }); } ``` This test runs on the VM, where `toXFile` is synchronous. It would not compile for the web, where the method returns a `Future`; run web tests with `flutter test --platform chrome` and `await` the result. ## Related Documentation - [Pick](https://anilcancakir.com/magic/docs/picker/basics/pick.md): the facade under test. - [XFile Conversion](https://anilcancakir.com/magic/docs/picker/basics/xfile.md): the two extensions and their platform split. - [Download](https://anilcancakir.com/magic/docs/picker/basics/download.md): the handler `PickerServiceProvider` installs.