Learn/Backend & Cloud/Generative AI & Gemini in Flutter

Generative AI & Gemini in Flutter

Integrate Google Gemini AI into Flutter apps with real-time streaming, multimodal inputs, and chat UIs

15 min~6 min read+60 FX

You can read this lesson publicly. Sign in to unlock exercises, quiz, and FX progress tracking.

Table of Contents

  1. 1. 1. Initializing the Gemini Model
  2. 2. Basic Single-Turn Request
  3. 3. 2. Real-Time Streaming Responses
  4. 4. 3. Multimodal AI (Images + Text)
  5. 5. This Lesson In Simple Words
  6. 6. Your level focus
  7. 7. One practical habit
  8. 8. Deep Understanding Guide
  9. 9. Why this lesson matters
  10. 10. Study flow for better retention
  11. 11. Quick Glossary
  12. 12. Architecture Lens

Having trouble? AI is here to help

Ask context-aware questions about this lesson. Free plan: 5 questions/day. Upgrade to Premium for higher daily limits.

Use the AI button at the bottom of the screen

Generative AI & Gemini in Flutter

Integrating Artificial Intelligence into mobile applications is one of the highest-value skills in modern software engineering. From intelligent chat assistants and personalized tutors to receipt scanning and image comprehension, modern apps leverage large language models (LLMs) to transform user experiences.

Google provides the official google_generative_ai Dart SDK, making it seamless to connect Flutter applications to the Gemini 1.5 family of models. In this lesson, you will learn how to configure Gemini, stream responses in real-time, and analyze multimodal images.

1. Initializing the Gemini Model

Add google_generative_ai to your pubspec.yaml. Then, initialize a GenerativeModel instance:

import 'package:google_generative_ai/google_generative_ai.dart';

final model = GenerativeModel(
  model: 'gemini-1.5-flash', // Fast, cost-efficient model ideal for mobile
  apiKey: const String.fromEnvironment('GEMINI_API_KEY'),
  systemInstruction: Content.system(
    'You are FlutterCraft AI, an expert, friendly mobile development tutor. '
    'Keep your explanations concise, encouraging, and provide code examples in Dart.',
  ),
);

Basic Single-Turn Request

Future<String?> askGemini(String prompt) async {
  final content = [Content.text(prompt)];
  final response = await model.generateContent(content);
  return response.text;
}

Secure Your API Key

💡 Secure Your API Key

Never hardcode API keys in source code! Pass them at build time using flutter run --dart-define=GEMINI_API_KEY=your_key or proxy requests through a secure backend server.

2. Real-Time Streaming Responses

In conversational apps, waiting 5 to 10 seconds for a full answer degrades user experience. Instead, use generateContentStream() to stream tokens to the UI as Gemini generates them!

dart
1import 'package:flutter/material.dart';
2import 'package:google_generative_ai/google_generative_ai.dart';
3
4class GeminiChatScreen extends StatefulWidget {
5 final GenerativeModel model;
6 const GeminiChatScreen({super.key, required this.model});
7
8 @override
9 State<GeminiChatScreen> createState() => _GeminiChatScreenState();
10}
11
12class _GeminiChatScreenState extends State<GeminiChatScreen> {
13 final TextEditingController _controller = TextEditingController();
14 String _streamedResponse = '';
15 bool _isLoading = false;
16
17 Future<void> _sendMessage() async {
18 final prompt = _controller.text.trim();
19 if (prompt.isEmpty) return;
20
21 _controller.clear();
22 setState(() {
23 _isLoading = true;
24 _streamedResponse = '';
25 });
26
27 try {
28 final content = [Content.text(prompt)];
29 // Stream tokens in real time:
30 final responseStream = widget.model.generateContentStream(content);
31
32 await for (final chunk in responseStream) {
33 if (!mounted) return;
34 setState(() {
35 _streamedResponse += chunk.text ?? '';
36 });
37 }
38 } catch (e) {
39 setState(() => _streamedResponse = 'Error: \\$e');
40 } finally {
41 if (mounted) setState(() => _isLoading = false);
42 }
43 }
44
45 @override
46 Widget build(BuildContext context) {
47 return Scaffold(
48 appBar: AppBar(title: const Text('Gemini AI Assistant')),
49 body: Padding(
50 padding: const EdgeInsets.all(16),
51 child: Column(
52 children: [
53 Expanded(
54 child: SingleChildScrollView(
55 child: Text(
56 _streamedResponse.isEmpty && !_isLoading
57 ? 'Ask any question about Flutter...'
58 : _streamedResponse,
59 style: const TextStyle(fontSize: 16, height: 1.5),
60 ),
61 ),
62 ),
63 if (_isLoading) const LinearProgressIndicator(),
64 const SizedBox(height: 12),
65 Row(
66 children: [
67 Expanded(
68 child: TextField(
69 controller: _controller,
70 decoration: const InputDecoration(
71 hintText: 'Ask Gemini...',
72 border: OutlineInputBorder(),
73 ),
74 ),
75 ),
76 const SizedBox(width: 8),
77 IconButton(
78 icon: const Icon(Icons.send),
79 onPressed: _isLoading ? null : _sendMessage,
80 ),
81 ],
82 ),
83 ],
84 ),
85 ),
86 );
87 }
88}

3. Multimodal AI (Images + Text)

Gemini excels at understanding images alongside text prompts. You can send image bytes directly using DataPart:

import 'dart:typed_data';

Future<String?> analyzeReceipt(Uint8List imageBytes) async {
  final prompt = TextPart('Extract the merchant name, total price, and date from this receipt.');
  final imagePart = DataPart('image/jpeg', imageBytes);

  final response = await model.generateContent([
    Content.multi([prompt, imagePart]),
  ]);

  return response.text;
}

Handling Rate Limits & Errors

⚠️ Handling Rate Limits & Errors

Free Gemini API keys carry requests-per-minute (RPM) limits. Always wrap API calls in try-catch blocks and display clear retry buttons or error states to users.

Mobile GenAI Checklist

  • Use gemini-1.5-flash for mobile chat interactions (low latency and high token budget).
  • Stream tokens using generateContentStream() to eliminate user perception of latency.
  • Use systemInstruction to define role constraints, safety boundaries, and persona tone.
  • Compress images before sending via DataPart to save user bandwidth and speed up responses.
  • Never expose raw API keys in client-side code; use compile-time constants or proxy backends.

This Lesson In Simple Words

Integrate Google Gemini AI into Flutter apps with real time streaming, multimodal inputs, and chat UIs. Dart is the language behind Flutter, and clear Dart code makes your Flutter UI easier to maintain.

Your level focus

Operate with production and interview-level clarity.

One practical habit

Prefer readable names, explicit intent, and async/await over deeply nested callbacks.

Deep Understanding Guide

Why this lesson matters

When Dart basics are weak, state bugs, null crashes, and async confusion increase quickly.

Study flow for better retention

  1. Tie each concept to scale, failure handling, and delivery strategy.
  2. Treat each Dart concept as a building block for widgets, services, and tests you will write later.
  3. If you can defend trade-offs under constraints, your understanding is strong.

Common Mistakes To Avoid

  • Ignoring null safety and forcing values with ! without checking data flow.
  • Writing long functions that mix validation, transformation, and side effects together.
  • Using dynamic where a proper type would catch mistakes earlier.
  • Catching broad errors without keeping useful context for debugging.

Practice Sprint (15-25 Minutes)

  • Before running sample code, predict output and behavior in one sentence.
  • Write a small pure function and test it with edge cases.
  • Convert one callback-based snippet to async/await with proper error handling.
  • Refactor a long function into smaller helper methods with clear names.
  • Complete the required exercises without using hints on the first attempt.
  • Answer this question out loud before checking quiz options: "Which official package is used to connect Flutter apps directly to Google Gemini models?".

Quick Glossary

  • stream: A sequence of asynchronous values over time.

Code Comprehension Drill

  • State the purpose of the code block in one line before reading details.
  • Mark inputs, state changes, and final output.
  • Change one small value and predict what should happen before running.
  • Run again and compare your prediction with actual behavior.

Architecture Lens

Strong Dart habits lead to predictable APIs and cleaner boundaries between presentation and business logic.

As your app grows, keep UI, state, and data responsibilities separate so each part stays testable and easier to modify.

Lesson Completion Checklist

  • I can explain "Generative AI & Gemini in Flutter" in simple words without reading notes.
  • I can describe one real app situation where this concept is required.
  • I know at least one mistake to avoid: Ignoring null safety and forcing values with ! without checking data flow.
  • I can modify one code sample and correctly predict the behavior change.
  • I can finish required exercises with understanding, not trial-and-error guesses.

Frequently Asked Questions

Which official package is used to connect Flutter apps directly to Google Gemini models?

google_generative_ai is Google's official Dart SDK for Gemini models.

Why should mobile chat UIs prefer generateContentStream() over generateContent()?

Streaming allows the user to read response tokens in real-time as they arrive rather than waiting for the entire paragraph to complete.

How do you send an image alongside a text prompt to Gemini?

Content.multi accepts multiple parts, including TextPart and binary DataPart for image data.

What is the purpose of systemInstruction in GenerativeModel configuration?

systemInstruction directs the model's overall behavior, persona, and output constraints across all subsequent prompts.

Suggest Improvement

Something seems incorrect, unclear, or missing? Let us know.

About The Author

FlutterCraft editorial lessons are reviewed by experienced Flutter developers and updated to stay aligned with modern Flutter and Dart best practices.

Reference docs: Flutter Documentation, Dart Language Tour, and official package documentation where relevant.

Sign in to continue with exercises and quiz for this lesson.

Sign In to Continue