Sub topic 6
Showing, saving, and uploading the result
This chapter covers what to do with an XFile after image_picker returns it. You will display it on mobile and web, copy it out of the temporary cache, and upload it as multipart form data.
It assumes you have read the chapters on picking images and on XFile, and that you are comfortable with async/await and StatefulWidget. You also need path_provider, path, http, and http_parser in pubspec.yaml.
What the picker actually gives you
A picked file is usually not yours yet. On Android and iOS the plugin writes it to a temporary cache directory, often after resizing or recompressing it when you set maxWidth or imageQuality. The OS can clear that directory at any time, and the plugin may overwrite it on later picks. Treat XFile.path as valid only for the current session.
The members you will use in this chapter:
| Member | Returns | Notes |
|---|---|---|
| `path` | `String` | A file path on mobile and a blob URL on web. |
| `name` | `String` | The file name without the directory. |
| `mimeType` | `String?` | Can be `null`. Do not rely on it. |
| `length()` | `Future<int>` | Size in bytes. |
| `readAsBytes()` | `Future<Uint8List>` | Loads the whole file into memory. |
| `openRead()` | `Stream<Uint8List>` | Reads in chunks without loading everything. |
| `saveTo(String path)` | `Future<void>` | Copies the file to the given path. |
Showing the image
On mobile, Image.file reads straight from the path. On web, the path is a blob URL, so Image.network is the right widget.
import 'dart:io';
import 'package:flutter/foundation.dart' show kIsWeb;
import 'package:flutter/material.dart';
import 'package:image_picker/image_picker.dart';
Widget previewOf(XFile file) {
if (kIsWeb) {
return Image.network(file.path, fit: BoxFit.cover);
}
return Image.file(
File(file.path),
fit: BoxFit.cover,
cacheWidth: 600,
);
}cacheWidth tells Flutter to decode the image at a smaller size. A 12-megapixel photo decoded at full size uses roughly 48 MB of memory as a bitmap, so a grid of thumbnails without cacheWidth can exhaust memory quickly. Pick a value close to the on-screen pixel width.
If you want one code path for every platform, load the bytes and use Image.memory.
import 'dart:typed_data';
import 'package:flutter/material.dart';
import 'package:image_picker/image_picker.dart';
class XFileImage extends StatelessWidget {
const XFileImage({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 Icon(Icons.broken_image);
}
final bytes = snapshot.data;
if (bytes == null) {
return const Center(child: CircularProgressIndicator());
}
return Image.memory(bytes, fit: BoxFit.cover, cacheWidth: 600);
},
);
}
}This widget has a flaw. file.readAsBytes() runs inside build, so every rebuild starts a new read and the image flickers. For anything beyond a demo, create the Future once in initState of a StatefulWidget, or read the bytes in the code that handles the pick and keep them in state.
Showing several images
pickMultiImage returns a List<XFile>, which you can hand to a grid. Give each tile a stable key so Flutter keeps the right state when the list changes.
import 'package:flutter/material.dart';
import 'package:image_picker/image_picker.dart';
class PickedGrid extends StatelessWidget {
const PickedGrid({super.key, required this.files});
final List<XFile> files;
@override
Widget build(BuildContext context) {
return GridView.builder(
gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount(
crossAxisCount: 3,
mainAxisSpacing: 4,
crossAxisSpacing: 4,
),
itemCount: files.length,
itemBuilder: (context, index) {
final file = files[index];
return XFileImage(key: ValueKey(file.path), file: file);
},
);
}
}This reuses XFileImage from the previous example. The picker's cache paths are unique per file, so the path works as a key.
Saving to a permanent location
To keep a photo across app restarts, copy it from the cache into a directory your app owns. getApplicationDocumentsDirectory() from path_provider is the usual choice for user content that should persist and be included in backups. getApplicationSupportDirectory() suits files that users should not see.
import 'dart:io';
import 'package:image_picker/image_picker.dart';
import 'package:path/path.dart' as p;
import 'package:path_provider/path_provider.dart';
Future<File> persist(XFile file) async {
final dir = await getApplicationDocumentsDirectory();
final baseName = file.name.isEmpty ? 'photo.jpg' : p.basename(file.name);
final stamp = DateTime.now().millisecondsSinceEpoch;
final target = p.join(dir.path, '${stamp}_$baseName');
await file.saveTo(target);
return File(target);
}Three details matter here:
- The timestamp prefix prevents two picks with the same cache name from overwriting each other.
- Store the relative file name, or rebuild the path from
getApplicationDocumentsDirectory()at launch, rather than saving the absolute path in a database. On iOS the app container path can change between installs and updates, which invalidates stored absolute paths. saveTois not available as a real file copy on web. There it triggers a download or writes through the browser's APIs, so skip persistence code on web or branch onkIsWeb.
Uploading
For uploads, send the file as multipart/form-data. Stream the file with openRead() instead of calling readAsBytes(), so a 20 MB photo or a long video is not loaded into memory at once. A streamed MultipartFile needs the byte length up front, which length() provides.
import 'package:http/http.dart' as http;
import 'package:http_parser/http_parser.dart';
import 'package:image_picker/image_picker.dart';
Future<bool> uploadPhoto(XFile file, Uri url) async {
final request = http.MultipartRequest('POST', url)
..fields['caption'] = 'Uploaded from Flutter'
..files.add(
http.MultipartFile(
'photo',
file.openRead(),
await file.length(),
filename: file.name,
contentType: MediaType.parse(
file.mimeType ?? 'application/octet-stream',
),
),
);
try {
final response = await request.send().timeout(
const Duration(seconds: 30),
);
await response.stream.drain<void>();
return response.statusCode >= 200 && response.statusCode < 300;
} on Exception {
return false;
}
}Points to check in this code:
'photo'is the form field name. It must match what your server expects.mimeTypecan benull, so the code falls back to a generic type. If your server validates content types, derive the type from the file extension instead, for example with themimepackage.response.stream.drain()releases the connection even though the code ignores the body.- The
timeoutis onsend(), so it covers the time until the response headers arrive. It does not limit a slow upload that keeps making progress. - The function returns
falsefor both a network failure and a rejected request. In a real app, return a result type so the UI can tell "no connection, retry later" from "server refused this file".
Large files and progress
http gives no upload progress. If you need a progress bar, use dio with FormData and onSendProgress, or wrap the stream from openRead() in a Stream.transform that counts bytes as they pass through. Either way, keep the file on disk until the server confirms receipt.
Cleaning up
The cache holds copies of everything you picked. Clean up once you no longer need a file.
- If you copied the file with
saveTo, the cache copy is redundant. Delete it withFile(file.path).delete()inside atryblock, and ignore aPathNotFoundException. - If you uploaded the file and do not keep a local copy, delete the cache file after the server confirms success.
- If an upload fails, keep the file so a retry can use it. If your app can be closed before the retry, copy it to the documents directory first and upload from there.
import 'dart:io';
import 'package:image_picker/image_picker.dart';
Future<void> deleteCacheCopy(XFile file) async {
try {
await File(file.path).delete();
} on FileSystemException {
// Already gone, or not a real file path. Nothing to do.
}
}Common mistakes
- Storing
file.pathfrom the cache in a database and expecting it to work next week. - Using
Image.fileon web. - Reading full-size bytes for every thumbnail, with no
cacheWidth. - Calling
readAsBytes()inbuild. - Assuming
mimeTypeis non-null. - Deleting the cache file before the upload has finished.
Exercise
A user picks a photo, you show it, and you upload it. The upload fails because the phone has no signal, and the user closes the app. Which of the following preserves the retry: (a) keeping file.path from the picker, or (b) copying the file with saveTo into the documents directory before the first upload attempt? Explain why, and say what you would store in your database.
Show answer
Option (b). The picker's path points into a cache directory that the OS or the plugin can clear, so after the app closes the file may be gone. Copying it with saveTo into getApplicationDocumentsDirectory() gives you a file you control. Store the relative file name (or a generated ID plus the file name) and a status such as "pending upload", then rebuild the full path at launch from the documents directory. Delete the file only after the server confirms the upload.
Exercise
Why does a picker grid that shows twenty full-resolution photos with Image.file and no cacheWidth risk running out of memory, and how do you fix it?
Show answer
Flutter decodes each image at its full pixel size, which is about 4 bytes per pixel. A 12-megapixel photo takes roughly 48 MB decoded, so twenty of them need close to 1 GB. Set cacheWidth (or cacheHeight) to about the on-screen pixel size, for example 600, so each image is decoded at a smaller size. You can also use imageQuality and maxWidth in the picker call to shrink the files before they reach the UI.