This Flutter tutorial will teach us how to build the Flutter ChatGPT app properly. Everything will be discussed step by step and with a proper practical example in order for better understanding.
The complete source code will also be provided at the end. But make sure to follow all the steps as every step is crucial in creating this chat GPT app in Flutter.
Introduction: Flutter ChatGPT App
You may already know the trend of ChatGPT. It gives the users a unique messaging experience that is powered by Artificial Intelligence. We just have to provide it an input and it’ll generate an appropriate response to this input using natural language processing and machine learning algorithms.
In this tutorial, we’ll learn how to create a Flutter chatBot app. We’ll understand the following concepts:
Create UI – It’s used to take inputs from the user and display the response data.
Configurations – We’ll import the required package in order to use chatGPT in the Flutter app.
Operations – We’ll go through the required functions that are used to send and receive data.
Implementing Flutter ChatGPT App (Step By Step)
Follow the below steps and don’t skip any, or else you may run into some problems.
Step 1: Import Chat GPT SDK Package
chat_gpt_sdk: git: url: https://github.com/iampawan/Flutter-ChatGPT.git
import 'package:chat_gpt_sdk/chat_gpt_sdk.dart';
Then use this statement in the dart file where you want to use the chat GPT SDK.
Step 2: Get the API Key
https://beta.openai.com/account/api-keys
We’ve to get our own API key using this URL. We’ll need it in order to get access to the information.
Step 3: Create UI
We’ve created a simple Flutter template that will show the list of input and responses using the Flutter list view builder. Also, we’ve used the Flutter textfield widget to get the input(question) from the user. See the below image.
Flutter widgets and other Flutter concepts that are used in creating this UI are as follows.
Flutter container widget
Flutter text widget
Flutter column widget
Flutter row widget
Flutter textfield widget
Flutter circular progress indicator widget
Flutter padding widget
Flutter appbar widget
Flutter sized box widget
Flutter listview builder
Flutter if else statement
Flutter set state
Flutter expanded widget
Check out our previous articles in case we miss some widgets. Also, we’ve written detailed articles on these Flutter widgets so do check them out as well.
Step 4: Coding
TextEditingController question = TextEditingController();
final List<dynamic> messagesList = [];
This list will store the messages. It’s a list of maps. It’ll include questions and answers.
ChatGPT? chatGPT; StreamSubscription? subscription;
Functions
@override void initState() { super.initState(); chatGPT = ChatGPT.instance.builder( "use your own api key here" // https://beta.openai.com/account/api-keys ); }
Function to Send and Receive Information
void sendMessage() { setState(() { showLoading = true; if (question.text.isNotEmpty) { messagesList.add({'sender': 'Me', 'text': question.text}); } String questionData = question.text; question.clear(); final request = CompleteReq( prompt: questionData, model: kTranslateModelV3, max_tokens: 200); subscription = chatGPT!.onCompleteStream(request: request).listen((responseData) { setState(() {}); if (showLoading) { messagesList.add( {'sender': 'Bot', 'text': responseData!.choices[0].text.trim()}); } showLoading = false; }); }); }
This function will get the data(answer) using the question provided by the user.
Dispose
@override void dispose() { chatGPT!.close(); question.dispose(); subscription?.cancel(); super.dispose(); }
Step 5: Test the Flutter ChatGPT App
So this is how we can easily create the Flutter ChatGPT app. Hope you like this post and have learned a lot from it. Don’t hesitate to share it with other Flutter developers.
Ask if you have any questions/suggestions regarding this Flutter ChatGPT app. We’d love to read it.
The complete source code is given in the below section.
Flutter ChatGPT App Complete Source Code
import 'dart:async'; import 'package:chat_gpt_sdk/chat_gpt_sdk.dart'; import 'package:flutter/material.dart'; void main() { runApp(const MyApp()); } class MyApp extends StatelessWidget { const MyApp({Key? key}) : super(key: key); @override Widget build(BuildContext context) { return MaterialApp( debugShowCheckedModeBanner: false, title: 'Flutter ChatGPT App', home: ChatGPTScreen()); } } class ChatGPTScreen extends StatefulWidget { const ChatGPTScreen({super.key}); @override State<ChatGPTScreen> createState() => _ChatGPTScreenState(); } class _ChatGPTScreenState extends State<ChatGPTScreen> { TextEditingController question = TextEditingController(); final List<dynamic> messagesList = []; ChatGPT? chatGPT; StreamSubscription? subscription; bool showLoading = false; @override void initState() { super.initState(); chatGPT = ChatGPT.instance.builder( "user your own API key here" // https://beta.openai.com/account/api-keys ); } void sendMessage() { setState(() { showLoading = true; if (question.text.isNotEmpty) { messagesList.add({'sender': 'Me', 'text': question.text}); } final request = CompleteReq( prompt: question.text, model: kTranslateModelV3, max_tokens: 200); question.clear(); subscription = chatGPT!.onCompleteStream(request: request).listen((responseData) { setState(() {}); if (showLoading) { messagesList.add( {'sender': 'Bot', 'text': responseData!.choices[0].text.trim()}); } showLoading = false; }); }); } @override void dispose() { chatGPT!.close(); question.dispose(); subscription?.cancel(); super.dispose(); } @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( centerTitle: true, backgroundColor: Colors.blue.shade900, title: Text('Flutter ChatGPT'), ), body: SizedBox( height: double.infinity, width: double.infinity, child: Column(children: [questionAnswersList(), inputTextField()]), ), ); } Widget inputTextField() { return Align( alignment: Alignment.bottomCenter, child: Padding( padding: EdgeInsets.all(11), child: TextField( controller: question, readOnly: showLoading ? true : false, cursorColor: Colors.blue.shade400, decoration: InputDecoration( enabledBorder: OutlineInputBorder( borderSide: BorderSide(color: Colors.blue.shade200, width: .5)), focusedBorder: OutlineInputBorder( borderSide: BorderSide(color: Colors.blue.shade300)), hintText: showLoading ? 'AI is writing...' : 'Ask your question...', hintStyle: TextStyle(color: Colors.grey.shade500, fontSize: 14), suffixIcon: InkWell( onTap: (){ if(question.text.isNotEmpty){ sendMessage(); } }, child: showLoading ? Padding( padding: EdgeInsets.all(11), child: CircularProgressIndicator( strokeWidth: 1.7, ), ) : Icon( Icons.send, color: Colors.blue.shade900, ), )), ), ), ); } Widget questionAnswersList() { return Expanded( child: ListView.builder( itemCount: messagesList.length, padding: EdgeInsets.symmetric(vertical: 21), itemBuilder: ((context, index) { return Padding( padding: EdgeInsets.all(11), child: SizedBox( child: Row( children: [ Container( padding: EdgeInsets.all(11), decoration: BoxDecoration( shape: BoxShape.circle, color: messagesList[index]['sender'] == 'Me' ? Colors.white : Colors.blue.shade900, boxShadow: [ BoxShadow( color: Colors.grey.shade300, blurRadius: 3, spreadRadius: 1, offset: Offset(1, 1)) ]), child: Text( messagesList[index]['sender'], style: TextStyle( color: messagesList[index]['sender'] == 'Bot' ? Colors.white : Colors.blue.shade900, fontSize: 13), ), ), Expanded( child: Container( margin: EdgeInsets.only(left: 11), padding: EdgeInsets.all(11), decoration: BoxDecoration( borderRadius: BorderRadius.circular(11), color: Colors.white, boxShadow: [ BoxShadow( color: Colors.grey.shade300, blurRadius: 3, spreadRadius: 1, offset: Offset(1, 1)) ]), child: Text( messagesList[index]['text'], style: TextStyle(color: Colors.black87, fontSize: 14), ), ), ) ], ), ), ); })), ); } }
Conclusion
In conclusion, we hope you now have a detailed and practical understanding of how to implement the Flutter chatGPT app. We’d be very glad to have your valuable feedback.
We’d also be glad to see you visit our other tutorials on Flutter app development. Thank you for reading this article.