Last active
February 18, 2024 07:07
-
-
Save AdnanKhan45/c274dace32302cf4516025bc25ffaa57 to your computer and use it in GitHub Desktop.
Example Flutter code to build a ChatBot using google_generative_ai package.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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