Skip to content

Instantly share code, notes, and snippets.

@AdnanKhan45
Last active February 18, 2024 07:07
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save AdnanKhan45/c274dace32302cf4516025bc25ffaa57 to your computer and use it in GitHub Desktop.
Save AdnanKhan45/c274dace32302cf4516025bc25ffaa57 to your computer and use it in GitHub Desktop.
Example Flutter code to build a ChatBot using google_generative_ai package.
// Import necessary packages
import 'package:flutter/material.dart';
import 'package:google_generative_ai/google_generative_ai.dart';
// Replace with your actual API key
const apiKey = 'YOUR_API_KEY';
// Main app widget
class MyChatApp extends StatefulWidget {
@override
_MyChatAppState createState() => _MyChatAppState();
}
class _MyChatAppState extends State<MyChatApp> {
final TextEditingController textController = TextEditingController();
List<String> messages = []; // Stores chat history
bool isGenerating = false;
void sendMessage(String text) async {
setState(() => isGenerating = true);
// Create GenerativeModel instance
final model = GenerativeModel(model: 'gemini-pro', apiKey: apiKey);
// Prepare request content
final content = [Content.text(text)];
// Generate response
final response = await model.generateContent(content);
print("response $response");
print("text ${response.text}");
// Add messages to chat history
setState(() {
messages.add(response.text!);
isGenerating = false;
});
}
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
appBar: AppBar(title: Text('Chatbot')),
body: Column(
children: [
// Chat history display
Expanded(
child: ListView.builder(
itemCount: messages.length,
itemBuilder: (context, index) {
return Text(messages[index]);
},
),
),
isGenerating == true
? Center(child: CircularProgressIndicator())
: Container(),
// User input field
Row(
children: [
Expanded(
child: TextField(
controller: textController,
onSubmitted: (text) => sendMessage(text),
),
),
IconButton(
icon: Icon(Icons.send),
onPressed: () {
sendMessage(textController.text);
setState(() {
messages.add(textController.text);
});
textController.clear();
}, // Get text from field
),
],
),
],
),
),
);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment