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.
Integrate Google Gemini AI into Flutter apps with real-time streaming, multimodal inputs, and chat UIs
You can read this lesson publicly. Sign in to unlock exercises, quiz, and FX progress tracking.
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
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.
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.',
),
);
Future<String?> askGemini(String prompt) async {
final content = [Content.text(prompt)];
final response = await model.generateContent(content);
return response.text;
}
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.
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!
1import 'package:flutter/material.dart';2import 'package:google_generative_ai/google_generative_ai.dart';34class GeminiChatScreen extends StatefulWidget {5final GenerativeModel model;6const GeminiChatScreen({super.key, required this.model});78@override9State<GeminiChatScreen> createState() => _GeminiChatScreenState();10}1112class _GeminiChatScreenState extends State<GeminiChatScreen> {13final TextEditingController _controller = TextEditingController();14String _streamedResponse = '';15bool _isLoading = false;1617Future<void> _sendMessage() async {18final prompt = _controller.text.trim();19if (prompt.isEmpty) return;2021_controller.clear();22setState(() {23_isLoading = true;24_streamedResponse = '';25});2627try {28final content = [Content.text(prompt)];29// Stream tokens in real time:30final responseStream = widget.model.generateContentStream(content);3132await for (final chunk in responseStream) {33if (!mounted) return;34setState(() {35_streamedResponse += chunk.text ?? '';36});37}38} catch (e) {39setState(() => _streamedResponse = 'Error: \\$e');40} finally {41if (mounted) setState(() => _isLoading = false);42}43}4445@override46Widget build(BuildContext context) {47return Scaffold(48appBar: AppBar(title: const Text('Gemini AI Assistant')),49body: Padding(50padding: const EdgeInsets.all(16),51child: Column(52children: [53Expanded(54child: SingleChildScrollView(55child: Text(56_streamedResponse.isEmpty && !_isLoading57? 'Ask any question about Flutter...'58: _streamedResponse,59style: const TextStyle(fontSize: 16, height: 1.5),60),61),62),63if (_isLoading) const LinearProgressIndicator(),64const SizedBox(height: 12),65Row(66children: [67Expanded(68child: TextField(69controller: _controller,70decoration: const InputDecoration(71hintText: 'Ask Gemini...',72border: OutlineInputBorder(),73),74),75),76const SizedBox(width: 8),77IconButton(78icon: const Icon(Icons.send),79onPressed: _isLoading ? null : _sendMessage,80),81],82),83],84),85),86);87}88}
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;
}
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.
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.
Operate with production and interview-level clarity.
Prefer readable names, explicit intent, and async/await over deeply nested callbacks.
When Dart basics are weak, state bugs, null crashes, and async confusion increase quickly.
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.
google_generative_ai is Google's official Dart SDK for Gemini models.
Streaming allows the user to read response tokens in real-time as they arrive rather than waiting for the entire paragraph to complete.
Content.multi accepts multiple parts, including TextPart and binary DataPart for image data.
systemInstruction directs the model's overall behavior, persona, and output constraints across all subsequent prompts.
Something seems incorrect, unclear, or missing? Let us know.
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