Table of Contents
Welcome to the ultimate guide for setting up your Flutter project with seamless AI integration. Whether you're a beginner or an experienced developer, this step-by-step tutorial will help you get started quickly and efficiently.
Prerequisites
- Basic knowledge of Flutter and Dart programming language
- Flutter SDK installed on your machine
- An IDE such as Android Studio or Visual Studio Code
- Access to an AI service provider (e.g., OpenAI, Google Cloud AI)
- API keys from your chosen AI provider
Step 1: Create a New Flutter Project
Open your terminal or command prompt and run the following command to create a new Flutter project:
flutter create ai_integration_app
Navigate into your project directory:
cd ai_integration_app
Step 2: Add Dependencies
Open pubspec.yaml and add the following dependencies for HTTP requests and JSON parsing:
dependencies:
flutter:
sdk: flutter
http: ^0.13.4
flutter_dotenv: ^5.0.2
Save the file and run:
flutter pub get
Step 3: Configure Environment Variables
Create a .env file in the root of your project and add your API key:
AI_API_KEY=your_api_key_here
Ensure to add .env to your .gitignore file to keep your keys secure.
Step 4: Initialize Environment Variables
In your main.dart, initialize dotenv:
import 'package:flutter_dotenv/flutter_dotenv.dart';
void main() async {
await dotenv.load(fileName: ".env");
runApp(MyApp());
}
Step 5: Create AI Service Helper
Make a new Dart file ai_service.dart to handle API requests:
import 'dart:convert';
import 'package:http/http.dart' as http;
import 'package:flutter_dotenv/flutter_dotenv.dart';
class AIService {
final String apiKey = dotenv.env['AI_API_KEY'] ?? '';
Future getAIResponse(String prompt) async {
final url = Uri.parse('https://api.openai.com/v1/completions');
final response = await http.post(
url,
headers: {
'Content-Type': 'application/json',
'Authorization': 'Bearer $apiKey',
},
body: jsonEncode({
'model': 'text-davinci-003',
'prompt': prompt,
'max_tokens': 150,
}),
);
if (response.statusCode == 200) {
final data = jsonDecode(response.body);
return data['choices'][0]['text'].toString().trim();
} else {
throw Exception('Failed to fetch AI response');
}
}
}
Step 6: Build the User Interface
Update main.dart to include a simple UI for input and output:
import 'package:flutter/material.dart';
import 'ai_service.dart';
void main() async {
await dotenv.load(fileName: ".env");
runApp(MyApp());
}
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'AI Integration Demo',
home: ChatScreen(),
);
}
}
class ChatScreen extends StatefulWidget {
@override
_ChatScreenState createState() => _ChatScreenState();
}
class _ChatScreenState extends State {
final TextEditingController _controller = TextEditingController();
String _response = '';
final AIService _aiService = AIService();
bool _isLoading = false;
void _sendPrompt() async {
setState(() {
_isLoading = true;
_response = '';
});
try {
final reply = await _aiService.getAIResponse(_controller.text);
setState(() {
_response = reply;
});
} catch (e) {
setState(() {
_response = 'Error: $e';
});
} finally {
setState(() {
_isLoading = false;
});
}
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: Text('AI Integration Demo')),
body: Padding(
padding: const EdgeInsets.all(16.0),
child: Column(
children: [
TextField(
controller: _controller,
decoration: InputDecoration(
labelText: 'Enter your prompt',
border: OutlineInputBorder(),
),
),
SizedBox(height: 10),
ElevatedButton(
onPressed: _isLoading ? null : _sendPrompt,
child: Text('Send'),
),
SizedBox(height: 20),
_isLoading
? CircularProgressIndicator()
: Expanded(
child: SingleChildScrollView(
child: Text(
_response,
style: TextStyle(fontSize: 16),
),
),
),
],
),
),
);
}
}
Final Tips
Always keep your API keys secure and avoid exposing them in public repositories. Test your app thoroughly to handle errors gracefully. With this setup, you can now expand your app's capabilities by integrating more AI features and customizing the UI.