firebase-ai
Firebase AI Skill
This skill defines how to correctly use Firebase AI Logic in Flutter applications.
When to Use
Use this skill when:
- Setting up and configuring Firebase AI in a Flutter project.
- Generating text content or chat responses with Gemini models.
- Implementing streaming AI responses for real-time UI updates.
- Sending multimodal prompts (text + images) to Gemini.
- Handling errors, offline scenarios, and rate limits for AI operations.
- Applying security and privacy considerations for AI features.
1. Setup and Configuration
flutter pub add firebase_ai
import 'package:firebase_ai/firebase_ai.dart';
import 'package:firebase_core/firebase_core.dart';
import 'firebase_options.dart';
// Initialize FirebaseApp
await Firebase.initializeApp(
options: DefaultFirebaseOptions.currentPlatform,
);
// Initialize the Gemini Developer API backend service
final model =
FirebaseAI.googleAI().generativeModel(model: 'gemini-2.5-flash');
- Ensure the Firebase project is configured for AI services via the Firebase AI Logic page in the Firebase Console.
- Initialize Firebase before using any Firebase AI features.
- Use
FirebaseAI.googleAI()for the Gemini Developer API backend (recommended starting point). - Implement App Check to prevent abuse of Firebase AI endpoints.
Platform support:
| Platform | Support |
|---|---|
| iOS | Full |
| Android | Full |
| Web | Full |
| macOS / other Apple | Beta |
| Windows | Not supported |
2. Generating Content
Single-turn text generation
final response = await model.generateContent([
Content.text('Summarize the benefits of Flutter for mobile development'),
]);
final text = response.text; // The generated summary string
Multi-turn chat
final chat = model.startChat();
final response = await chat.sendMessage(
Content.text('What is the difference between StatelessWidget and StatefulWidget?'),
);
print(response.text);
// Follow-up in the same conversation
final followUp = await chat.sendMessage(
Content.text('When should I use StatefulWidget?'),
);
print(followUp.text);
Streaming responses
Use streaming to display partial results as they arrive:
final stream = model.generateContentStream([
Content.text('Write a step-by-step guide to implementing dark mode in Flutter'),
]);
await for (final chunk in stream) {
// Append chunk.text to the UI progressively
setState(() => _output += chunk.text ?? '');
}
Multimodal prompts (text + image)
final imageBytes = await File('photo.jpg').readAsBytes();
final response = await model.generateContent([
Content.multi([
TextPart('Describe what you see in this image'),
InlineDataPart('image/jpeg', imageBytes),
]),
]);
3. Error Handling
Wrap AI calls in structured error handling:
try {
final response = await model.generateContent([Content.text(prompt)]);
return response.text;
} on FirebaseAIException catch (e) {
if (e.message?.contains('quota') ?? false) {
// Handle rate limiting — show retry message or queue the request
return 'Service is busy. Please try again shortly.';
}
return 'AI service error: ${e.message}';
} catch (e) {
return 'Unexpected error: $e';
}
- Provide meaningful error messages to users when AI operations fail.
- Handle offline scenarios with appropriate fallback behavior (e.g., cached responses).
- Implement exponential backoff for rate-limited or transient errors.
4. Security and Privacy
- Follow Firebase Security Rules best practices when using AI services alongside other Firebase products.
- Ensure proper authentication and authorization for AI feature access.
- Sanitize user input before sending it to the model to prevent prompt injection.
- Be mindful of data privacy requirements when processing user content with AI services.
- Implement appropriate content filtering and moderation using safety settings:
final model = FirebaseAI.googleAI().generativeModel(
model: 'gemini-2.5-flash',
safetySettings: [
SafetySetting(HarmCategory.harassment, HarmBlockThreshold.medium),
SafetySetting(HarmCategory.dangerousContent, HarmBlockThreshold.high),
],
);
References
More from evanca/flutter-ai-rules
riverpod
Uses Riverpod for state management in Flutter/Dart. Use when setting up providers, combining requests, managing state disposal, passing arguments, performing side effects, testing providers, or applying Riverpod best practices.
28bloc
Implement Flutter state management using the bloc and flutter_bloc libraries. Use when creating a new Cubit or Bloc, modeling state with sealed classes or status enums, wiring BlocBuilder/BlocListener/BlocProvider in widgets, writing bloc unit tests, refactoring state management, or deciding between Cubit and Bloc.
21effective-dart
Apply Effective Dart guidelines to write idiomatic, high-quality Dart and Flutter code. Use when writing new Dart code, reviewing pull requests for style compliance, refactoring naming conventions, adding doc comments, structuring imports, enforcing type annotations, or running code review checks against Effective Dart standards.
20flutter-app-architecture
Implement layered Flutter app architecture with MVVM, repositories, services, and dependency injection. Use when scaffolding a new Flutter project, refactoring an existing app into layers, creating view models and repositories, configuring dependency injection, implementing unidirectional data flow, or adding a domain layer for complex business logic.
18testing
Write, review, and improve Flutter and Dart tests including unit tests, widget tests, and golden tests. Use when writing new tests, reviewing test quality, fixing flaky tests, adding test coverage, structuring test files, or choosing between unit and widget tests.
16architecture-feature-first
Structure Flutter apps using layered architecture (UI / Logic / Data) with feature-first file organization. Use when creating new features, designing the project folder structure, adding repositories, services, view models (or cubits/providers/notifiers), wiring dependency injection, or deciding which layer owns a piece of logic. State management agnostic.
16