Adding ChatGPT, Gemini or Claude to a Flutter app takes an afternoon in a prototype and a lot longer in production. The hard parts are not the API call; they are keeping keys secret, making responses feel fast on a phone, getting reliable data out of a model, and keeping the bill predictable. I have shipped LLM features in TourVista (an AI travel guide), Nest AI, Fluently AI and GAIA, and this is the architecture I now use by default.
What use cases make sense for LLMs in a mobile app?
LLMs fit best where users would otherwise type, read or search a lot: chat assistants, summarization, extraction from photos or documents, and personalised recommendations. They fit poorly where answers must be exact every time, like prices or medical dosages, unless you ground them in your own data and validate the output.
- Conversational assistants: in-app support or a domain guide, like TourVista's travel guide.
- Summarization: condensing notes, PDFs or long threads into something readable on a small screen.
- Multi-modal input: Fluently AI combined Google ML Kit on-device OCR, Whisper speech-to-text and GPT-4 so users could learn from text and voice.
- Generation: GAIA used DALL-E for image generation, which follows the same proxy pattern as text.
What is the right architecture for LLMs in Flutter?
The app talks only to your backend, and your backend talks to the model provider: Flutter app → authenticated proxy → model API. The proxy holds the API key, checks who the user is, applies limits and forwards a stream back to the app.
Flutter app --(Firebase ID token, HTTPS)--> Proxy (Cloud Function / Vercel / Edge)
| checks auth, rate limit, max tokens
| adds system prompt, provider key
v
OpenAI / Gemini / Claude
Flutter app <--(SSE stream of text deltas)-- Proxy
Never put a provider API key in the app, including in --dart-define, .env assets or obfuscated strings. Anything in the binary can be extracted, and a leaked key is billed to you. I wrote a full walkthrough of this in Stop Hardcoding LLM API Keys in Flutter. Nest AI, a privacy-focused app, used exactly this setup: a secure proxy to OpenAI, with conversations stored on the device in AES-256 encrypted Hive boxes.
The proxy has a second benefit: the system prompt and provider choice live on the server. You can fix a bad prompt or switch from one provider to another without waiting for App Store review.
Which LLM provider should you use: OpenAI, Gemini or Claude?
All three are capable enough for most mobile features, so choose on fit: the ecosystem you already use, the modalities you need and how each model behaves on your own test prompts. Model names and prices change often, so check each provider's docs at the time you build rather than trusting a comparison table, including this one.
| Provider | Where it tends to fit well | Flutter integration approach |
|---|---|---|
| OpenAI (ChatGPT models) | Broad ecosystem, structured outputs, speech (Whisper) and image generation under one account | Call from your proxy with the official server SDK; stream SSE to the app |
| Google Gemini | Multi-modal input (images, audio, long documents), close integration with Firebase and Google Cloud | Server-side Gemini API, or Firebase's AI client SDKs, which keep keys off the device and work with App Check |
| Anthropic Claude | Long-context reading, careful instruction following, tool use for structured results | Call from your proxy with the official SDK; stream SSE to the app |
My practical advice: build a small evaluation set of 20 to 30 real prompts from your app, run them against each provider through the proxy, and compare quality, latency and cost per request. That beats any generic benchmark for your use case.
How do you stream LLM responses in Flutter with SSE?
Have the proxy return text/event-stream, read the response body as a stream in Dart, split it into lines and yield each data: payload. Streaming is what makes an AI feature feel responsive: in TourVista, the first token reached the screen in under 500ms, even though full answers took longer to finish.
import 'dart:async';
import 'dart:convert';
import 'package:http/http.dart' as http;
/// Streams text deltas from your proxy. The proxy normalises every
/// provider to: data: {"delta":"..."} and ends with data: [DONE]
Stream<String> streamChat({
required http.Client client,
required String idToken,
required List<Map<String, String>> messages,
}) async* {
final request = http.Request(
'POST',
Uri.parse('https://api.example.com/chat/stream'),
)
..headers.addAll({
'Authorization': 'Bearer $idToken',
'Content-Type': 'application/json',
'Accept': 'text/event-stream',
})
..body = jsonEncode({'messages': messages});
final response = await client
.send(request)
.timeout(const Duration(seconds: 15)); // time to first byte
if (response.statusCode != 200) {
throw LlmException(response.statusCode, await response.stream.bytesToString());
}
final lines = response.stream
.transform(utf8.decoder)
.transform(const LineSplitter());
await for (final line in lines.timeout(const Duration(seconds: 30))) {
if (!line.startsWith('data:')) continue; // skip comments and blank lines
final data = line.substring(5).trim();
if (data == '[DONE]') break;
final delta = (jsonDecode(data) as Map<String, dynamic>)['delta'] as String?;
if (delta != null && delta.isNotEmpty) yield delta;
}
}
class LlmException implements Exception {
LlmException(this.statusCode, this.body);
final int statusCode;
final String body;
}
Two details are worth copying. First, decode with utf8.decoder on the byte stream, not per chunk, so multi-byte characters split across network chunks do not break. Second, let the proxy convert each provider's own event format into one simple shape, so the Flutter code does not change when you switch provider.
On the UI side, append deltas to a buffer in your state layer (a Riverpod Notifier, a BLoC or a GetX controller) and rebuild only the message being generated. Rebuilding the whole chat list on every token is a common cause of jank; my Flutter performance tips cover how to keep rebuilds narrow.
How do you get reliable structured JSON from an LLM?
Use the provider's structured output feature (a JSON schema, JSON response mode or tool calling) on the server, and then validate the result in Dart before the app trusts it. Asking for JSON in the prompt alone works most of the time, which is not good enough for a feature users depend on.
class Place {
Place({required this.name, required this.lat, required this.lng, required this.summary});
final String name;
final double lat;
final double lng;
final String summary;
static Place? tryParse(Map<String, dynamic> json) {
final name = json['name'], lat = json['lat'], lng = json['lng'], summary = json['summary'];
if (name is! String || lat is! num || lng is! num || summary is! String) return null;
if (lat.abs() > 90 || lng.abs() > 180) return null; // models can invent coordinates
return Place(name: name, lat: lat.toDouble(), lng: lng.toDouble(), summary: summary);
}
}
Return null on invalid data and show a fallback, rather than crashing or rendering half a card. For anything factual, such as places, prices or availability, ground the model with your own data and treat its output as a suggestion that your code checks.
How do you control LLM costs in a mobile app?
Enforce cost limits on the server: cap output tokens per request, trim conversation history, cache repeated answers and rate-limit each user. Client-side limits do not count, because anyone can call your proxy directly once they find the URL. For a worked per-user estimate, see what AI features cost to run.
- Token limits: set a maximum output length per endpoint. A summary does not need the same budget as a long chat reply.
- History trimming: send the last few turns plus a short running summary instead of the entire conversation every time.
- Caching: cache answers to repeated, non-personal questions on the server, and keep previous results on the device. TourVista cached content in SQLite so places a user had already viewed loaded offline without another model call.
- Rate limiting: limit requests per user per minute and per day, keyed on the verified user ID. Tie higher limits to a paid plan if the feature is monetised.
- Provider prompt caching: several providers discount repeated prompt prefixes, so keep long system prompts stable and at the start of the request.
- Debouncing: do not call the model on every keystroke in search-style features.
Should you use on-device or cloud models?
Use cloud models for open-ended reasoning and generation, and on-device models for narrow, latency-sensitive or privacy-sensitive tasks. On-device models are smaller, available only on some devices, and increase app size if you bundle them yourself, but they work offline and keep data on the phone.
The approach I use most is a hybrid. In Fluently AI, text recognition ran on the device with Google ML Kit, so the cloud model only needed to work with extracted text rather than raw images. Platform-provided on-device models from Apple and Google are worth evaluating for small tasks like rewriting or classification, but check device support carefully and always keep a cloud fallback. I compare ML Kit, LiteRT and Gemini Nano with a cloud API in On-device AI in Flutter.
How should you handle errors and timeouts?
Expect every LLM request to fail sometimes, and design for it: time out early, retry only safe cases, and keep partial output visible. Users forgive a slow answer far more readily than a frozen screen.
- Two timeouts: a short one for the first byte, and an idle timeout between chunks, as in the code above.
- Retry with backoff on network errors, 429 and 5xx responses, but not on 400s, which will fail the same way again.
- Keep partial text if the stream drops, mark the message as incomplete and offer a "Continue" or "Retry" action.
- Cancel on navigation: close the
http.Clientor cancel the stream subscription when the user leaves the screen, so you are not paying for tokens nobody will read. - Human error messages: map provider errors on the proxy into a few app-level cases (rate limited, unavailable, content blocked) and never show raw provider JSON.
What did TourVista teach me about shipping an LLM app?
TourVista is an AI travel guide that streams answers from OpenAI over SSE, caches content in SQLite for offline use, and uses adaptive GPS polling to save battery. We shipped it on iOS and Android in about four weeks. The lessons that carried over to every AI app since:
- Perceived speed is time to first token. Getting the first words on screen in under 500ms mattered more than total generation time.
- Offline is a feature. Travellers lose signal. Caching previous answers made the app useful without a connection and reduced repeat model calls.
- The model is one component. Location, caching and battery behaviour took as much engineering as the AI part.
The full story is in the TourVista case study, and the wider development workflow is in how I build Flutter apps with AI in 2026.
Frequently Asked Questions
Can I call the OpenAI API directly from Flutter?
Technically yes, but you should not in a production app. Calling directly means the API key is in the binary, where it can be extracted and abused at your expense. Route requests through a backend proxy that authenticates users, applies rate limits and holds the key. The extra hop adds very little latency when responses are streamed.
Which is better for Flutter: ChatGPT, Gemini or Claude?
None is best for every app. Gemini fits teams already on Firebase and Google Cloud and handles multi-modal input well; OpenAI has a broad set of APIs in one place; Claude is strong at long documents and careful instruction following. Test all three on your real prompts through the same proxy, then decide.
How do I stream ChatGPT responses in Flutter?
Have your proxy request a streaming response from the provider and forward it to the app as Server-Sent Events. In Dart, send the request with http.Client.send, decode the byte stream with utf8.decoder, split it with LineSplitter, and parse each data: line into a text delta that you append to the UI.
How much does it cost to add AI to a Flutter app?
There are two costs: building the feature and running it. Running costs depend on usage, model choice and prompt length, so estimate by measuring tokens per request on real prompts and multiplying by expected volume. Server-side token limits, caching and per-user rate limits keep that cost predictable as usage grows.
Do LLM features work offline in Flutter?
Cloud models need a connection, but you can cache previous answers locally so users still see useful content offline, as TourVista does with SQLite. For narrow tasks such as OCR or classification, on-device models work fully offline. Most production apps combine both approaches.
If you are adding AI to a Flutter app and want it secure, fast and affordable to run, see my Flutter AI development service or get in touch to talk through your use case.