A user is halfway through a support message, taps the camera icon, takes a photo of the broken screen, and lands back on your app's home page. The conversation is closed, the draft is gone and so is the photo. On the days the photo does survive, the request to your backend comes back with 413 Payload Too Large or a size error from the vision model.
These are two separate bugs in a hand-built AI support chat, and both have a fix. If you would sooner not own this code, the widget_chat package ships a finished chat screen with camera and gallery attachments built in (snippet at the end).
Why the app restarts after the camera on Android
image_picker opens the camera as a separate activity. The camera is memory hungry, so on a low-RAM phone Android may kill your backgrounded MainActivity to make room. When the user confirms the photo, Android starts your app again from scratch. The Future that pickImage returned died with the old process, so its result never arrives.
The plugin's docs describe this case and give you retrieveLostData(), an Android-only call that hands back the result on the next launch. FlutterFlow apps are Flutter apps underneath, so a FlutterFlow app that restarts when using the camera is hitting the same Android behaviour. The fix goes in custom code.
Treat it as a chat problem, not a picker problem
Most guides stop at calling retrieveLostData(). That gets you a file, but a file with no context. After a cold start your app does not know which conversation was open or what the user had typed. So the recovery needs three pieces.
- Persist before launchSave the conversation id and the draft text to disk before calling pickImage.
- Recover on startupCall retrieveLostData() once when the app starts and read the saved context.
- ReattachReopen the conversation, restore the draft and attach the recovered photo to it.
- ShrinkResize and compress the photo before it goes to your endpoint.
1. Persist the conversation and draft before the camera opens
import 'dart:convert';
import 'package:shared_preferences/shared_preferences.dart';
class PendingAttachment {
static const _key = 'pending_attachment';
static Future<void> save(String conversationId, String draft) async {
final prefs = await SharedPreferences.getInstance();
await prefs.setString(
_key,
jsonEncode({'conversationId': conversationId, 'draft': draft}),
);
}
static Future<Map<String, dynamic>?> take() async {
final prefs = await SharedPreferences.getInstance();
final raw = prefs.getString(_key);
if (raw == null) return null;
await prefs.remove(_key);
return jsonDecode(raw) as Map<String, dynamic>;
}
}
The pick itself saves first and clears after. If the process is killed, the clear never runs, and that leftover record is how the next launch knows there is something to restore.
final _picker = ImagePicker();
Future<void> attachFromCamera() async {
await PendingAttachment.save(conversation.id, composer.text);
final photo = await _picker.pickImage(source: ImageSource.camera);
await PendingAttachment.take(); // normal return: nothing to recover
if (photo != null) await attach(photo);
}
2. Recover with retrieveLostData on relaunch
Call this once at startup, after the first frame so you have a navigator to push on.
import 'package:flutter/foundation.dart';
import 'package:image_picker/image_picker.dart';
Future<void> recoverLostPhoto() async {
if (kIsWeb || defaultTargetPlatform != TargetPlatform.android) return;
final pending = await PendingAttachment.take();
if (pending == null) return;
final response = await ImagePicker().retrieveLostData();
final files = response.files;
final chat = await openConversation(pending['conversationId'] as String);
chat.composer.text = pending['draft'] as String;
if (response.exception != null) {
chat.showError('Could not load the photo, please try again.');
} else if (!response.isEmpty && files != null && files.isNotEmpty) {
await chat.attach(files.first);
}
}
openConversation, composer and attach are your own chat code. Two details matter here. The draft is restored even when no photo comes back, because the user cancelling in the camera after a process kill is still a lost draft. And response.exception is a normal pick error (a denied permission, for instance), not the reason the activity was destroyed, so handle it like any failed pick.
retrieveLostData only
- App reopens on the home screen
- Photo recovered but attached to nothing
- Typed message is gone
- User starts the ticket again
Persist, recover, reattach
- App reopens the same conversation
- Photo sits in the composer
- Draft text is back
- User taps send
Why the upload fails: 413 and vision size errors
A modern phone camera produces a 12 MP JPEG of several megabytes. Most hand-built chats send it to their own endpoint as base64 inside a JSON body, and base64 adds a third: every 3 bytes become 4 characters.
| Limit | Where it bites | What you see |
|---|---|---|
nginx client_max_body_size, 1 MB by default |
Your reverse proxy, before your code runs | 413 Request Entity Too Large |
| Body limits in your framework or serverless host | Your endpoint | 413 or a parse error |
| Model provider request and image limits | The vision call your backend makes | A validation or size error |
The nginx default surprises people most, because the request never reaches the handler you are debugging. And on the model side, extra pixels buy nothing: one major provider's vision docs say images with a long edge over 1568 px are scaled down on the standard tier before the model sees them. You pay upload time for detail that is thrown away. Limits differ per provider, so check the docs for yours.
Resize and compress with flutter_image_compress before upload
Run every attachment through one function, whether it came from the camera, the gallery or retrieveLostData.
import 'package:flutter_image_compress/flutter_image_compress.dart';
import 'package:path_provider/path_provider.dart';
Future<XFile> shrinkForUpload(XFile photo) async {
const budget = 700 * 1024; // bytes, leaves room for base64 and JSON under 1 MB
final dir = await getTemporaryDirectory();
final stamp = DateTime.now().millisecondsSinceEpoch;
XFile? out;
for (final quality in [80, 65, 50]) {
out = await FlutterImageCompress.compressAndGetFile(
photo.path,
'${dir.path}/upload_${stamp}_$quality.jpg',
minWidth: 1176,
minHeight: 1176,
quality: quality,
format: CompressFormat.jpeg,
);
if (out != null && await out.length() <= budget) break;
}
return out ?? photo;
}
minWidth and minHeight are oddly named. The plugin scales the image down, keeping its aspect ratio, until one side reaches those values, and it never upscales. With both set to 1176, the short edge of a 4:3 photo lands on 1176 and the long edge on 1568, in portrait or landscape. The docs say quality does not map linearly to file size, which is why the loop checks the real byte count instead of trusting one setting.
Then send it to your own endpoint:
import 'dart:convert';
import 'package:http/http.dart' as http;
Future<http.Response> sendWithImage(String conversationId, String text, XFile photo) async {
final small = await shrinkForUpload(photo);
final bytes = await small.readAsBytes();
debugPrint('image: ${await photo.length()} -> ${bytes.length} bytes');
return http.post(
Uri.parse('https://api.example.com/chat/messages'),
headers: {'Content-Type': 'application/json'},
body: jsonEncode({
'conversationId': conversationId,
'text': text,
'image': {'mediaType': 'image/jpeg', 'data': base64Encode(bytes)},
}),
);
}
Worked example: before and after
Take a typical 4000 x 3000 camera JPEG of 3.6 MB. As base64 it becomes 4.8 MB, nearly five times the nginx default. Resized to 1568 x 1176 at quality 80, a photo like this comes out around 320 KB, or about 427 KB as base64.
Request size for one camera photo
The debugPrint line in sendWithImage gives you the same before and after for your own devices.
Checklist
- Conversation id and draft saved to disk before pickImage
- retrieveLostData() called once on Android startup
- Draft restored even when no photo comes back
- Every attachment resized and compressed through one function
- Base64 body checked against your proxy limit, not just the file size
- Tested with "Don't keep activities" switched on
Or skip the plumbing with widget_chat
Everything above is maintenance you take on when you build the chat screen yourself, along with the backend in front of the model. Widget-Chat is the alternative: the widget_chat package gives your Flutter or FlutterFlow app the whole chat screen, with image attachments from camera or gallery built in, chat history, and answers drawn from your own content. There is no chat backend to build or host, and the model provider key stays server-side.
flutter pub add widget_chat
ChatWidget(
configuration: BotConfiguration(
projectSecretKey: 'your-project-secret-key',
userID: 'user-123',
),
)
In FlutterFlow, add widget_chat as a custom pub dependency and use it in a custom widget (this needs a paid FlutterFlow plan). The FlutterFlow guide walks through it.
The free plan needs no credit card: create your Widget-Chat project.





