Sub topic 3
Understanding XFile
Both image_picker and camera return photos and videos as XFile objects. This chapter covers what an XFile contains, how it behaves on each platform, and the mistakes that follow from treating it as a plain dart:io File. It assumes you know async/await and Futures, and that you can add packages in pubspec.yaml. The picker and camera calls themselves come in later chapters.
What XFile is
XFile comes from the cross_file package. image_picker and camera both depend on it and re-export it, so a single import 'package:image_picker/image_picker.dart'; or import 'package:camera/camera.dart'; gives you the type.
The reason for the type is that dart:io's File does not exist on Flutter web. An XFile gives you one API that works on Android, iOS, web, and desktop. The API reads the data without assuming the data lives in a normal file on disk.
import 'package:image_picker/image_picker.dart';
Future<void> describe(XFile file) async {
print('path: ${file.path}');
print('name: ${file.name}');
print('mimeType: ${file.mimeType}');
print('bytes: ${await file.length()}');
print('modified: ${await file.lastModified()}');
}The members you will use
| Member | Type | Notes |
|---|---|---|
| `path` | `String` | A file path on mobile and desktop. A `blob:` URL on web. |
| `name` | `String` | File name with extension. Safe to display or send as an upload filename. |
| `mimeType` | `String?` | May be `null`. Do not rely on it. |
| `length()` | `Future<int>` | Size in bytes. Does not load the whole file into memory. |
| `lastModified()` | `Future<DateTime>` | Last modification time. |
| `readAsBytes()` | `Future<Uint8List>` | Loads the entire file into memory. |
| `readAsString()` | `Future<String>` | Decodes the content as text (UTF-8 by default). |
| `openRead([start, end])` | `Stream<Uint8List>` | Streams the content, optionally a byte range. |
| `saveTo(path)` | `Future<void>` | Writes a copy to the given location. |
Note that length() and lastModified() are methods that return Futures, not properties. Writing file.length compiles as a tear-off of the method, and then fails at the point where you use it as a number.
Where the data lives
An XFile is a handle. The bytes live somewhere else, and where depends on the platform and on how the file was produced.
- Gallery picks on Android and iOS. The plugin copies the selected item into the app's cache or temporary directory and gives you that path. It is not the original in the user's gallery. Deleting or editing it does not affect the original.
- Camera captures with
image_picker. The system camera app saves the photo, and the plugin returns a path to a copy. - Camera captures with
camera.takePicture()andstopVideoRecording()return anXFilepointing at a file in the app's temporary storage. - Web. There is no file system path.
pathis ablob:URL, and the bytes stay in browser memory.
Temporary means temporary
The cache location is the most common source of bugs. The operating system can clear the app's cache at any time, usually when storage is low and often between launches. If you store file.path in a database and read it next week, the file may be gone.
If the image must outlive the session, copy it to a durable location right away. This example uses path_provider and path, which you add to pubspec.yaml:
import 'dart:io';
import 'package:image_picker/image_picker.dart';
import 'package:path/path.dart' as p;
import 'package:path_provider/path_provider.dart';
/// Copies [file] into the app documents directory and returns the new path.
/// Not for web: there is no documents directory there.
Future<String> persist(XFile file) async {
final Directory dir = await getApplicationDocumentsDirectory();
final String target = p.join(dir.path, file.name);
await file.saveTo(target);
return target;
}Two details matter here. First, file.name can collide with an existing file, since camera apps often generate names from a counter or timestamp. If uniqueness matters, build your own name, for example from DateTime.now().microsecondsSinceEpoch plus the extension from p.extension(file.name). Second, store the new path, not the original file.path.
Reading content without assuming dart:io
Because path is not always a real file, code that does File(file.path) works on mobile and breaks on web. When you need the data, use the XFile methods. They behave the same on every platform.
For a preview that works everywhere, read the bytes and use Image.memory:
import 'dart:typed_data';
import 'package:flutter/material.dart';
import 'package:image_picker/image_picker.dart';
class XFilePreview extends StatelessWidget {
const XFilePreview({super.key, required this.file});
final XFile file;
@override
Widget build(BuildContext context) {
return FutureBuilder<Uint8List>(
future: file.readAsBytes(),
builder: (context, snapshot) {
if (snapshot.hasError) {
return const Text('Could not read image');
}
final Uint8List? bytes = snapshot.data;
if (bytes == null) {
return const CircularProgressIndicator();
}
return Image.memory(bytes, fit: BoxFit.cover);
},
);
}
}One caveat: FutureBuilder restarts the future whenever future: receives a new object. Calling file.readAsBytes() inside build creates a new Future on every rebuild, which rereads the file. For a stable screen this is acceptable. For a screen that rebuilds often, create the Future once in initState or cache the bytes.
readAsBytes() loads the whole file. A 12-megapixel JPEG is a few megabytes, which is fine. A video can be hundreds of megabytes, which is not. For large data, use the stream:
import 'package:image_picker/image_picker.dart';
/// Reads only the first three bytes to check for the JPEG signature.
Future<bool> looksLikeJpeg(XFile file) async {
final List<int> head = <int>[];
await for (final chunk in file.openRead(0, 3)) {
head.addAll(chunk);
}
return head.length == 3 &&
head[0] == 0xFF &&
head[1] == 0xD8 &&
head[2] == 0xFF;
}A signature check like this is more reliable than mimeType or the file extension, because either of those can be missing or wrong.
Choosing the right access method
- To show an image on every platform, use
readAsBytes()withImage.memory. - To show an image on mobile only and avoid holding bytes in memory, use
Image.file(File(file.path)). Guard it withkIsWeb, frompackage:flutter/foundation.dart. - To upload a large file, stream it with
openRead()and passlength()as the content length. - To keep the file, call
saveTo()into a directory you control. - To check size before processing, call
length()and compare it to your limit before loading anything.
Common errors
FileSystemExceptionor an unsupported-operation error on web. You usedFile(file.path)orImage.file. Switch toreadAsBytes()or, for display,Image.network(file.path)on web.- A saved path that stops working. You stored the cache path. Copy the file to the documents directory and store that path.
- Out-of-memory crashes on video. You called
readAsBytes()on a large file. Stream withopenRead(). - Using
lengthas a number. It is a method returning a Future. Writeawait file.length(). - Assuming
nameis unique. Two picks can share a name. Generate your own when you keep files. - Expecting
saveToto write a file on web. On web it starts a browser download instead of writing to a path you can read back.
Exercise
A user picks a photo on Android. Your app stores file.path in a local database. Two days later the app opens the saved record and the image fails to load. What happened, and how do you fix it?
Show answer
The path pointed to a temporary copy in the app's cache, and the operating system cleared it. Fix it by copying the file into a durable directory right after picking, for example with await file.saveTo(p.join(documentsDir.path, uniqueName)) using the path from getApplicationDocumentsDirectory(), and then storing the new path.
Exercise
Your preview widget uses Image.file(File(file.path)) and works on a phone, but shows an error in Chrome. Give a version that works on both and explain why the original fails.
Show answer
On web, path is a blob: URL, not a file system path, so File(file.path) cannot open it. Use FutureBuilder<Uint8List> over file.readAsBytes() and render the bytes with Image.memory. That route uses only XFile methods, which are implemented on every platform.