Here is a simple, clear, and complete guide to using AI in a Flutter application, including text AI (ChatGPT/Gemini), image generation, speech, and on-device AI.
π How to Use AI in a Flutter Application
Below are the 4 most common ways developers use AI in Flutter:
β 1. Using AI via Cloud APIs (OpenAI, Gemini, Claude, etc.)
π₯ Best for:
- Chatbots
- Text generation
- Summaries
- AI assistants
- Image generation (DALLΒ·E, Gemini, etc.)
Example: Using OpenAI (ChatGPT) API in Flutter
Step 1: Add Dependencies
dependencies:
http: ^1.2.0
flutter_dotenv: ^5.1.0
Step 2: Create .env file
OPENAI_API_KEY=your_openai_key_here
Step 3: Create API Service
import 'dart:convert';
import 'package:http/http.dart' as http;
import 'package:flutter_dotenv/flutter_dotenv.dart';
class OpenAIService {
final String apiKey = dotenv.env['OPENAI_API_KEY']!;
Future<String> sendMessage(String message) async {
final url = Uri.parse("https://api.openai.com/v1/chat/completions");
final response = await http.post(
url,
headers: {
"Content-Type": "application/json",
"Authorization": "Bearer $apiKey",
},
body: jsonEncode({
"model": "gpt-4o-mini",
"messages": [
{"role": "user", "content": message}
]
}),
);
final data = jsonDecode(response.body);
return data["choices"][0]["message"]["content"];
}
}
Step 4: Use in UI
OpenAIService ai = OpenAIService();
String response = await ai.sendMessage("Hello, what is Flutter?");
print(response);
β 2. Using Google’s Gemini API (Free Option Available)
Step 1: Add Dependency
dependencies:
google_generative_ai: ^0.4.3
Step 2: Use Gemini in Flutter
import 'package:google_generative_ai/google_generative_ai.dart';
final model = GenerativeModel(
model: "gemini-pro",
apiKey: "YOUR_API_KEY",
);
Future<void> runAI() async {
final response = await model.generateContent(
[Content.text("Explain Flutter in simple words")]
);
print(response.text);
}
β 3. Using On-Device AI (No Internet Required)
You can use on-device AI with:
β TensorFlow Lite (TFLite)
β Firebase ML Kit
β PyTorch Mobile
Example: TFLite Image Classification
Step 1: Add Dependencies
dependencies:
tflite_flutter: ^1.0.1
image: ^4.1.3
Step 2: Add Model to assets
assets:
- assets/model.tflite
Step 3: Load and Run Model
import 'package:tflite_flutter/tflite_flutter.dart';
void runModel() async {
final interpreter = await Interpreter.fromAsset('model.tflite');
var input = [1.0, 2.0, 3.0];
var output = List.filled(1 * 3, 0).reshape([1, 3]);
interpreter.run(input, output);
print(output);
}
β 4. Using AI Features in Firebase ML Kit
ML Kit supports:
- Face detection
- Text recognition
- Barcode scanning
- Voice transcription
- On-device translation
Example: Text Recognition
final textRecognizer = TextRecognizer();
final inputImage = InputImage.fromFilePath("assets/image.jpg");
final RecognizedText text = await textRecognizer.processImage(inputImage);
print(text.text);
π― What Type of AI Do You Want to Add?
Choose your goal:
0 Comments