flutter_ai_chat 0.0.1
flutter_ai_chat: ^0.0.1 copied to clipboard
AI chat interface with streaming responses and conversation management
import 'package:flutter/material.dart';
import 'package:flutter_ai_chat/flutter_ai_chat.dart';
import 'package:provider/provider.dart';
void main() {
runApp(const MyApp());
}
class MyApp extends StatelessWidget {
const MyApp({super.key});
@override
Widget build(BuildContext context) => MaterialApp(
title: 'Flutter AI Chat Example',
theme: ThemeData(
colorScheme: ColorScheme.fromSeed(seedColor: Colors.deepPurple),
useMaterial3: true,
),
home: const ChatExamplePage(),
);
}
class ChatExamplePage extends StatefulWidget {
const ChatExamplePage({super.key});
@override
State<ChatExamplePage> createState() => _ChatExamplePageState();
}
class _ChatExamplePageState extends State<ChatExamplePage> {
final AIService _aiService = AIService();
final ChatProvider _chatProvider = ChatProvider();
final TextEditingController _controller = TextEditingController();
@override
void initState() {
super.initState();
// Set your OpenAI API key here
_aiService.apiKey = 'your-api-key-here';
}
@override
Widget build(BuildContext context) => Scaffold(
appBar: AppBar(
backgroundColor: Theme.of(context).colorScheme.inversePrimary,
title: const Text('Flutter AI Chat Example'),
),
body: Column(
children: [
Expanded(
child: Consumer<ChatProvider>(
builder: (context, chatProvider, child) {
final currentConversation = chatProvider.currentConversation;
if (currentConversation == null) {
return const Center(
child: Text('Start a new conversation!'),
);
}
return ListView.builder(
itemCount: currentConversation.messages.length,
itemBuilder: (context, index) {
final message = currentConversation.messages[index];
return ListTile(
leading: Icon(
message.isUser ? Icons.person : Icons.smart_toy,
color: message.isUser ? Colors.blue : Colors.green,
),
title: Text(message.content),
subtitle: Text(
message.timestamp.toString(),
style: const TextStyle(fontSize: 12),
),
);
},
);
},
),
),
Padding(
padding: const EdgeInsets.all(16.0),
child: Row(
children: [
Expanded(
child: TextField(
controller: _controller,
decoration: const InputDecoration(
hintText: 'Type your message...',
border: OutlineInputBorder(),
),
),
),
const SizedBox(width: 8),
Consumer<ChatProvider>(
builder: (context, chatProvider, child) => ElevatedButton(
onPressed: chatProvider.isLoading
? null
: () async {
if (_controller.text.trim().isNotEmpty) {
await chatProvider
.sendMessage(_controller.text);
_controller.clear();
}
},
child: chatProvider.isLoading
? const CircularProgressIndicator()
: const Text('Send'),
),
),
],
),
),
],
),
floatingActionButton: FloatingActionButton(
onPressed: _chatProvider.createNewConversation,
tooltip: 'New Conversation',
child: const Icon(Icons.add),
),
);
@override
void dispose() {
_controller.dispose();
super.dispose();
}
}