Sub topic 7
Recovering from Android activity destruction
This chapter assumes you can already pick an image with image_picker and you know the StatefulWidget lifecycle. It covers a failure that only happens on Android. The user picks or captures a photo, and your app comes back with no result and no error.
Why the result can disappear
When you call pickImage with ImageSource.camera, Android starts the camera app on top of yours. Your app moves to the background. If the device is short on memory, the system can destroy your Android activity, and sometimes the whole process, while the camera app is in the foreground. Cameras use a lot of memory, so this happens most often on low-end phones.
When the user finishes, Android recreates your app. Your Dart code starts from main(), and the Future returned by pickImage no longer exists. The photo is on disk, but nothing in Dart is waiting for it.
The image_picker plugin saves the result on the Android side before your app is destroyed. You can fetch it with retrieveLostData() after the app restarts.
What survives and what does not
| Item | After the restart |
|---|---|
| The photo file | Still on disk |
| The plugin's cached result | Available once through `retrieveLostData()` |
| The pending `Future` from `pickImage` | Gone |
| Widget state, such as the `_image` field | Gone |
| Navigation stack | Gone, unless you use state restoration |
The last two rows matter. The plugin gives you back the file. It does not tell you which screen or form field the file was meant for. You have to rebuild that context yourself.
Calling retrieveLostData
retrieveLostData() returns a LostDataResponse. Check these members:
isEmptyistruewhen there is nothing to recover. This is the normal case on every launch that did not follow a destruction.filesis aList<XFile>?holding the recovered files. It can hold several entries if the user was picking multiple images.fileis the older single-file member. Preferfilesin current plugin versions.exceptionis aPlatformException?that is set when the pick failed.typeis aRetrieveType, eitherimageorvideo. It tells you which kind of pick was interrupted.
The method is meaningful only on Android. On iOS and web it returns an empty response, so a call on those platforms is harmless. The platform check in the example below is optional, but it states the intent.
A complete example
This screen starts a pick and also checks for lost data in initState.
import 'dart:io';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:image_picker/image_picker.dart';
class AvatarPage extends StatefulWidget {
const AvatarPage({super.key});
@override
State<AvatarPage> createState() => _AvatarPageState();
}
class _AvatarPageState extends State<AvatarPage> {
final ImagePicker _picker = ImagePicker();
XFile? _image;
String? _message;
@override
void initState() {
super.initState();
_recoverLostData();
}
Future<void> _recoverLostData() async {
if (kIsWeb || defaultTargetPlatform != TargetPlatform.android) return;
final LostDataResponse response = await _picker.retrieveLostData();
if (response.isEmpty) return;
if (!mounted) return;
final PlatformException? error = response.exception;
if (error != null) {
setState(() => _message = 'Recovery failed: ${error.code}');
return;
}
final List<XFile>? files = response.files;
if (response.type == RetrieveType.image &&
files != null &&
files.isNotEmpty) {
setState(() {
_image = files.first;
_message = 'Recovered your photo.';
});
}
}
Future<void> _takePhoto() async {
final XFile? picked = await _picker.pickImage(source: ImageSource.camera);
if (picked == null || !mounted) return;
setState(() => _image = picked);
}
@override
Widget build(BuildContext context) {
final XFile? image = _image;
return Scaffold(
appBar: AppBar(title: const Text('Avatar')),
body: Center(
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
if (image != null)
Image.file(File(image.path), height: 200, fit: BoxFit.cover)
else
const Icon(Icons.account_circle, size: 120),
if (_message != null) Text(_message!),
const SizedBox(height: 16),
FilledButton(
onPressed: _takePhoto,
child: const Text('Take photo'),
),
],
),
),
);
}
}The example uses PlatformException, which comes from package:flutter/services.dart. package:flutter/material.dart does not export it, so add this import:
import 'package:flutter/services.dart';Where to call it
Call retrieveLostData() as early as you can, once per app start. Two placements work:
- In
initStateof the screen that starts the pick, as above. This is simple, but it only works if that screen is the one shown after the restart. - In a startup routine, before the first screen is built. Store the recovered files in your state management layer, and let the right screen read them.
The cached result is handed out once. If you call the method twice, the second call returns an empty response. Do not call it speculatively from several widgets, because the first caller consumes the result.
Rebuilding the context
A recovered file is useless if you do not know what it was for. Suppose your form has an "ID front" slot and an "ID back" slot. After a restart, the recovered file could belong to either.
Save a small marker before you launch the picker, and read it back when you recover. A few options:
- Write the target slot name to
shared_preferencesbefore callingpickImage. Clear it when the result arrives normally. - Use Flutter's
RestorationMixinto restore navigation and form state, then read the lost-data result into the restored screen. - Pass the target through a route argument that your router restores.
The first option is the least code, and it works with any state management approach. The next snippet shows it.
import 'package:image_picker/image_picker.dart';
import 'package:shared_preferences/shared_preferences.dart';
Future<XFile?> pickForSlot(ImagePicker picker, String slot) async {
final SharedPreferences prefs = await SharedPreferences.getInstance();
await prefs.setString('pending_slot', slot);
final XFile? file = await picker.pickImage(source: ImageSource.camera);
await prefs.remove('pending_slot');
return file;
}If the app is destroyed during pickImage, the remove line never runs. On restart, a leftover pending_slot value together with a non-empty LostDataResponse tells you where the file belongs. If pending_slot exists but the response is empty, the user probably cancelled, and you can clear the marker.
Common mistakes
- Never calling
retrieveLostData(). The app works in every normal test and fails only on real, memory-starved devices. The user sees the form without the photo they just took. - Ignoring
exception. A response can be non-empty and still describe a failure. Checkexceptionbefore you readfiles. - Assuming the file is in a permanent location. Recovered files live in the same temporary storage as other picker results. Copy the file to your app's documents directory if you need to keep it, as described in the chapter on saving and uploading results.
- Using
setStatebeforemountedis checked. The recovery call is asynchronous, and the widget may have been disposed by the time it returns. - Expecting the
cameraplugin to need this. WithCameraController, the preview and capture happen inside your own activity, so there is no hand-off to another app. The lifecycle problems there are different and are handled by disposing and recreating the controller.
Testing the recovery path
You rarely get a destruction on demand, so force one:
- On an Android device or emulator, open Settings, Developer options, and turn on "Don't keep activities".
- Run your app and start a camera pick.
- Take the photo and confirm it.
- The app restarts, and your recovery code should show the photo.
This setting destroys the activity every time you leave it, which reproduces the situation on demand. Turn it off afterward, because it makes every other app behave oddly. On emulators you can also run adb shell am kill your.package.name while the camera app is open. This kills the background process in a way that resembles a low-memory kill.
Exercise
A user takes a photo for the "ID back" slot, and the app is destroyed by Android while the camera is open. After the restart, retrieveLostData() returns a non-empty response with one file. What two pieces of information do you still need before you can put that file in the right place, and how can you get each one?
Show answer
You need to know which slot the pick was for and whether the response is a success. Get the slot by saving a marker (for example pending_slot in shared_preferences) before calling pickImage and reading it after the restart. Get the success state by checking response.exception: if it is non-null the pick failed, and otherwise response.files holds the recovered photo.
Exercise
Why does the second call to retrieveLostData() in the same run usually return an empty response, and what does that mean for where you place the call?
Show answer
The plugin hands the cached result out once and then clears it. A second call finds nothing, so only the first caller gets the files. Call it in a single place, such as a startup routine or the one screen that starts the pick, and store the result in state that other widgets can read.