Flutter Setup for Firebase AI Logic
This guide covers how to integrate Firebase AI Logic (Gemini API) into your Flutter applications.
[!IMPORTANT] Foundational Workflows & CLI-First Approach:
- Review Foundation: Before implementing platform-specific code, ALWAYS review the foundational
firebase-basicsskill to ensure familiarity with core workflows.- Backend Provisioning via CLI: Use the Firebase CLI for backend setup. Running
npx firebase-tools init ailogicis MANDATORY to provision the service.flutterfire configuredoes NOT enable the AI service and will result inPERMISSION_DENIEDif skipped.- Client Configuration: Use
flutterfire configurestrictly for generatingfirebase_options.dart. Avoid manual Console configuration.
[!NOTE]
firebase_vertexaihas been replaced byfirebase_ai. Always usefirebase_aifor new projects.
Installation
Add the necessary Firebase dependencies to your pubspec.yaml:
dependencies:
flutter:
sdk: flutter
firebase_core: ^4.0.0
firebase_auth: ^6.0.0
firebase_ai: ^3.0.0Run flutter pub get to install the packages.
Initialization
Initialize Firebase and sign in (anonymously or via authenticated user) before using AI Logic.
import 'package:firebase_core/firebase_core.dart';
import 'package:firebase_auth/firebase_auth.dart';
import 'package:firebase_ai/firebase_ai.dart';
void main() async {
WidgetsFlutterBinding.ensureInitialized();
await Firebase.initializeApp();
await FirebaseAuth.instance.signInAnonymously();
runApp(const MyApp());
}Usage
Use FirebaseAI.googleAI for the Gemini Developer API.
[!IMPORTANT] Model Selection: Refer to Firebase AI Logic Models to find the latest supported model. Do not use old models like
gemini-2.0-proorgemini-2.0-flash.
[!IMPORTANT] Choose the Right API Provider: Always use
FirebaseAI.googleAI(Gemini Developer API) as the default for prototyping and standard use. Avoid using the Agent Platform Gemini API (formerly branded Vertex AI) unless the app and business use case specifically require enterprise-grade scalability or data residency requirements. Note that the Gemini Developer API usually does not require the Firebase project to be on the pay-as-you-go Blaze pricing plan; however, the Agent Platform Gemini API does require the Blaze plan.
Text Generation
import 'package:firebase_ai/firebase_ai.dart';
import 'package:firebase_auth/firebase_auth.dart';
Future<String> generateText(String prompt) async {
final googleAI = FirebaseAI.googleAI(auth: FirebaseAuth.instance);
// [AGENT] Replace '<latest_supported_model>' with the latest model from https://firebase.google.com/docs/ai-logic/models.md.txt
final model = googleAI.generativeModel(model: '<latest_supported_model>');
final response = await model.generateContent([Content.text(prompt)]);
return response.text ?? 'No response';
}Chat Session
final chat = model.startChat(history: [
Content.text('Hello, I am a user.'),
Content.model([TextPart('Hello! How can I help you today?')]),
]);
final response = await chat.sendMessage(Content.text('What is CBT?'));