Gemini AI in Flutter: solved exercise with multi-turn chat and google_generative_ai

Gemini AI in Flutter: solved exercise with multi-turn chat

google_generative_ai is Google’s official package for consuming the Gemini API directly from Dart. It supports sending prompts, maintaining multi-turn conversation context, and configuring model behavior from the client — no backend required for non-sensitive use cases.

Problem statement

Build a Gemini chat app that:

  • Configures GenerativeModel with gemini-1.5-flash and GenerationConfig.
  • Maintains conversation history with ChatSession (multi-turn context).
  • Shows a loading indicator while the model generates a response.
  • Handles API errors with clear messages.
  • Protects the API key using --dart-define instead of hardcoding it.

Dependencies

1
2
3
4
dependencies:
  flutter:
    sdk: flutter
  google_generative_ai: ^0.4.6

Configuration

1. Get an API key at Google AI Studio (free for development).

2. Run the app injecting the key as an environment variable to avoid writing it in code:

1
flutter run --dart-define=GEMINI_API_KEY=your_key_here

In production, use flavors or a secrets service (Google Secret Manager, AWS Secrets Manager, etc.).

Full solution

  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
import 'package:flutter/material.dart';
import 'package:google_generative_ai/google_generative_ai.dart';

// ── API key injected via --dart-define, never hardcoded ───────────────────────
const _apiKey = String.fromEnvironment('GEMINI_API_KEY');

Future<void> main() async {
  if (_apiKey.isEmpty) {
    throw Exception(
      'Run with: flutter run --dart-define=GEMINI_API_KEY=your_key',
    );
  }
  runApp(const MyApp());
}

class MyApp extends StatelessWidget {
  const MyApp({super.key});

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter + Gemini',
      theme: ThemeData(useMaterial3: true, colorSchemeSeed: Colors.indigo),
      home: const ChatPage(),
    );
  }
}

// ── Message model ─────────────────────────────────────────────────────────────
class ChatMessage {
  final String text;
  final bool isUser;
  final bool isLoading;

  const ChatMessage({
    required this.text,
    required this.isUser,
    this.isLoading = false,
  });
}

// ── ChatPage ──────────────────────────────────────────────────────────────────
class ChatPage extends StatefulWidget {
  const ChatPage({super.key});

  @override
  State<ChatPage> createState() => _ChatPageState();
}

class _ChatPageState extends State<ChatPage> {
  final _scrollCtrl = ScrollController();
  final _inputCtrl = TextEditingController();
  final _messages = <ChatMessage>[];
  late final ChatSession _chat;
  bool _sending = false;

  @override
  void initState() {
    super.initState();
    final model = GenerativeModel(
      model: 'gemini-1.5-flash',
      apiKey: _apiKey,
      generationConfig: GenerationConfig(
        temperature: 0.7,
        maxOutputTokens: 1024,
      ),
      systemInstruction: Content.system(
        'You are a Flutter programming assistant. '
        'Answer concisely, with code examples when useful.',
      ),
    );
    _chat = model.startChat();
  }

  @override
  void dispose() {
    _scrollCtrl.dispose();
    _inputCtrl.dispose();
    super.dispose();
  }

  void _scrollToBottom() {
    WidgetsBinding.instance.addPostFrameCallback((_) {
      if (_scrollCtrl.hasClients) {
        _scrollCtrl.animateTo(
          _scrollCtrl.position.maxScrollExtent,
          duration: const Duration(milliseconds: 300),
          curve: Curves.easeOut,
        );
      }
    });
  }

  Future<void> _sendMessage() async {
    final text = _inputCtrl.text.trim();
    if (text.isEmpty || _sending) return;

    _inputCtrl.clear();
    setState(() {
      _messages.add(ChatMessage(text: text, isUser: true));
      _messages.add(const ChatMessage(text: '', isUser: false, isLoading: true));
      _sending = true;
    });
    _scrollToBottom();

    try {
      final response = await _chat.sendMessage(Content.text(text));
      final replyText = response.text ?? '(no response)';
      setState(() {
        _messages.removeLast(); // remove loading indicator
        _messages.add(ChatMessage(text: replyText, isUser: false));
      });
    } on GenerativeAIException catch (e) {
      setState(() {
        _messages.removeLast();
        _messages.add(ChatMessage(text: 'API error: ${e.message}', isUser: false));
      });
    } catch (e) {
      setState(() {
        _messages.removeLast();
        _messages.add(ChatMessage(text: 'Unexpected error: $e', isUser: false));
      });
    } finally {
      if (mounted) setState(() => _sending = false);
      _scrollToBottom();
    }
  }

  @override
  Widget build(BuildContext context) {
    final colorScheme = Theme.of(context).colorScheme;
    return Scaffold(
      appBar: AppBar(
        title: const Text('Flutter + Gemini'),
        backgroundColor: colorScheme.primaryContainer,
        actions: [
          IconButton(
            icon: const Icon(Icons.delete_sweep_outlined),
            tooltip: 'Clear conversation',
            onPressed: () => setState(() => _messages.clear()),
          ),
        ],
      ),
      body: Column(
        children: [
          Expanded(
            child: _messages.isEmpty
                ? const Center(
                    child: Text(
                      'Ask something about Flutter',
                      style: TextStyle(color: Colors.grey),
                    ),
                  )
                : ListView.builder(
                    controller: _scrollCtrl,
                    padding: const EdgeInsets.all(16),
                    itemCount: _messages.length,
                    itemBuilder: (context, index) {
                      return _ChatBubble(message: _messages[index]);
                    },
                  ),
          ),
          _InputBar(
            controller: _inputCtrl,
            sending: _sending,
            onSend: _sendMessage,
          ),
        ],
      ),
    );
  }
}

// ── Chat bubble ───────────────────────────────────────────────────────────────
class _ChatBubble extends StatelessWidget {
  final ChatMessage message;

  const _ChatBubble({required this.message});

  @override
  Widget build(BuildContext context) {
    final colorScheme = Theme.of(context).colorScheme;
    final isUser = message.isUser;

    return Align(
      alignment: isUser ? Alignment.centerRight : Alignment.centerLeft,
      child: Container(
        margin: const EdgeInsets.only(bottom: 10),
        padding: const EdgeInsets.symmetric(horizontal: 14, vertical: 10),
        constraints: BoxConstraints(
          maxWidth: MediaQuery.of(context).size.width * 0.78,
        ),
        decoration: BoxDecoration(
          color: isUser
              ? colorScheme.primaryContainer
              : colorScheme.surfaceContainerHighest,
          borderRadius: BorderRadius.only(
            topLeft: const Radius.circular(16),
            topRight: const Radius.circular(16),
            bottomLeft: Radius.circular(isUser ? 16 : 4),
            bottomRight: Radius.circular(isUser ? 4 : 16),
          ),
        ),
        child: message.isLoading
            ? const SizedBox(
                width: 20,
                height: 20,
                child: CircularProgressIndicator(strokeWidth: 2),
              )
            : SelectableText(message.text),
      ),
    );
  }
}

// ── Input bar ─────────────────────────────────────────────────────────────────
class _InputBar extends StatelessWidget {
  final TextEditingController controller;
  final bool sending;
  final VoidCallback onSend;

  const _InputBar({
    required this.controller,
    required this.sending,
    required this.onSend,
  });

  @override
  Widget build(BuildContext context) {
    return SafeArea(
      child: Padding(
        padding: const EdgeInsets.fromLTRB(12, 4, 12, 8),
        child: Row(
          children: [
            Expanded(
              child: TextField(
                controller: controller,
                decoration: const InputDecoration(
                  hintText: 'Type a message...',
                  border: OutlineInputBorder(),
                  isDense: true,
                  contentPadding:
                      EdgeInsets.symmetric(horizontal: 12, vertical: 10),
                ),
                onSubmitted: (_) => onSend(),
                textInputAction: TextInputAction.send,
                maxLines: null,
              ),
            ),
            const SizedBox(width: 8),
            IconButton.filled(
              onPressed: sending ? null : onSend,
              icon: sending
                  ? const SizedBox(
                      width: 18,
                      height: 18,
                      child: CircularProgressIndicator(strokeWidth: 2),
                    )
                  : const Icon(Icons.send),
            ),
          ],
        ),
      ),
    );
  }
}

Key concepts

APIPurpose
GenerativeModelInitializes the model with name, API key and config
GenerationConfigControls temperature, max tokens, top-k, top-p
systemInstructionSystem instruction defining model behavior
model.startChat()Opens a ChatSession that maintains conversation history
chat.sendMessage()Sends a turn and returns GenerateContentResponse
response.textGenerated text (quick access to the first candidate)
Content.text()Builds a text message for the model
Content.system()System message (only in systemInstruction)
GenerativeAIExceptionTyped API error (quota, invalid key, safety)

Common mistakes

  • Empty or invalid API key: the model throws GenerativeAIException with a clear message. Verify you passed --dart-define=GEMINI_API_KEY=... correctly.
  • Hardcoding the API key in source code: anyone who decompiles the APK can extract it. Use --dart-define in development and a backend or secrets service in production.
  • Not managing the _sending flag: without a lock flag, the user can send multiple messages before receiving a response and desynchronize the history.
  • Not using SelectableText: Gemini responses often include code; SelectableText lets users copy the text, significantly improving the experience.

Practical application

This pattern is the foundation for onboarding assistants, content generators, semantic search features, and any functionality that enriches an app with generative AI. For production use cases with real users, Gemini calls should go through your own backend to control costs, add authentication, and log usage.

Guided practice and next step

FAQ

Is Gemini 1.5 Flash free?

Yes, within Google AI Studio free plan limits: 15 RPM (requests per minute) and 1,500 RPD (requests per day). For production with higher traffic, a paid plan is required.

What is the difference between gemini-1.5-flash and gemini-1.5-pro?

Flash is optimized for speed and cost; Pro for complex reasoning and long contexts. For most chat apps, Flash is the right choice.

How do I add streaming responses so text appears word by word?

Use chat.sendMessageStream(Content.text(text)) which returns Stream<GenerateContentResponse>. Accumulate the text on each event and call setState on each chunk to simulate real-time typing.