Sub topic 3
Understanding `XFile`
Assume you know Dart async and await, Flutter widget lifecycles, and how to add packages with pubspec.yaml. This chapter explains the file object returned by image_picker and camera.
What `XFile` represents
XFile is a cross-platform file abstraction from the cross_file package. It represents a file without forcing your app to use one platform's file API.
Both plugins use it:
image_pickerreturns anXFile?for one selected image or video.image_pickerreturnsList<XFile>for multiple images.camerareturns anXFileafter taking a picture or recording a video.
The nullable result from a picker means that the user canceled the operation. A successful result is an XFile object.
An XFile does not decode an image or provide image-editing operations. It gives your app access to the selected media and metadata.
| Member | Purpose |
|---|---|
| `name` | The file name, such as `photo.jpg` |
| `path` | A platform-specific location or URL |
| `readAsBytes()` | Reads the complete file into memory |
| `openRead()` | Provides a byte stream |
| `length()` | Gets the file size |
| `lastModified()` | Gets the modification time |
Use the path carefully
On Android and iOS, path is usually a local filesystem path. You can use dart:io and Image.file there.
On the web, dart:io is unavailable. The path may be a browser blob URL, so use a web-compatible widget such as Image.network. Code that handles every Flutter platform should prefer bytes or use conditional platform-specific code.
import 'dart:io';
import 'package:flutter/material.dart';
import 'package:image_picker/image_picker.dart';
Widget mobilePreview(XFile file) {
return Image.file(
File(file.path),
fit: BoxFit.cover,
);
}The function above is mobile-only because it imports dart:io. For a cross-platform preview, read the bytes:
import 'package:flutter/material.dart';
import 'package:image_picker/image_picker.dart';
class XFilePreview extends StatelessWidget {
const XFilePreview({
required this.file,
super.key,
});
final XFile file;
@override
Widget build(BuildContext context) {
return FutureBuilder<List<int>>(
future: file.readAsBytes(),
builder: (context, snapshot) {
if (!snapshot.hasData) {
return const Center(child: CircularProgressIndicator());
}
return Image.memory(
Uint8List.fromList(snapshot.data!),
fit: BoxFit.cover,
);
},
);
}
}Add dart:typed_data to use Uint8List:
import 'dart:typed_data';For large videos or images, readAsBytes() can use substantial memory. Prefer openRead() when an API accepts a stream, or upload the file using a platform-specific file mechanism.
Upload or preserve the file
An XFile returned by a picker may be stored in a temporary location. If your app needs the media after a restart, copy it into app-managed storage or upload it immediately.
For a byte-based multipart upload, the http package can use the file name while remaining independent of the local path:
import 'package:http/http.dart' as http;
import 'package:image_picker/image_picker.dart';
Future<http.Response> uploadImage(XFile file) async {
final request = http.MultipartRequest(
'POST',
Uri.parse('https://example.com/upload'),
);
request.files.add(
http.MultipartFile.fromBytes(
'image',
await file.readAsBytes(),
filename: file.name,
),
);
final response = await request.send();
return http.Response.fromStream(response);
}The picker can also return null, so check the result before using it. Android may destroy the activity while another application handles the picker. The recovery method for that case is covered separately.
Exercise
Why can code that calls Image.file(File(file.path)) fail on Flutter web?
Show answer
It imports dart:io and assumes that path is a local filesystem path. On the web, use a web-compatible URL or read the XFile bytes and display them with Image.memory.