Movatterモバイル変換


[0]ホーム

URL:


Skip to content
DEV Community
Log in Create account

DEV Community

Zuhaib Ahmad
Zuhaib Ahmad

Posted on • Originally published atzuhaibahmad.com on

Building a ChatGPT App with Flutter

Flutter is a state-of-the-art cross-platform mobile development framework owned by Google that allows developers to create visually stunning, high-performance native applications for iOS, Android, and web. On the other hand, ChatGPT is an AI model that utilizes the power of GPT to generate human-like responses to chat messages.

In this tutorial, we'll be putting both technologies together to create a ChatGPT application using Flutter. We'll be utilizing the Dart programming language and Flutter's widgets to communicate with ChatGPT API and display the chat interface.

Prerequisites

Before we start building our application, you'll need to set up your development environment. Here are the necessary prerequisites:

  • Flutter SDK installed on your machine.
  • An IDE, such as Android Studio, IntelliJ IDEA, or Visual Studio Code.
  • A working knowledge of Flutter and Dart.

Setting up the Application

  1. Create a new project in your IDE of choice.
  2. Add thehttp package and theflutter_dotenv package to yourpubspec.yaml file using thedependencies property.
dependencies:flutter:sdk:flutterhttp:^0.12.2flutter_dotenv:^4.0.0
Enter fullscreen modeExit fullscreen mode
  1. Create a.env file in your project's root directory and add your ChatGPT API key.
OPENAI_API_KEY=<YOUR_API_KEY>
Enter fullscreen modeExit fullscreen mode
  1. Import the necessary packages in yourmain.dart file.
import'dart:convert';import'package:flutter/material.dart';import'package:http/http.dart'ashttp;import'package:flutter_dotenv/flutter_dotenv.dart';
Enter fullscreen modeExit fullscreen mode
  1. Create aChatPage class that will display the chat interface and handle the user's input.
classChatPageextendsStatefulWidget{constChatPage({super.key});@overrideChatPageStatecreateState()=&gt;ChatPageState();}classChatPageStateextendsState&lt;ChatPage&gt;{// Map of messages and whether they were sent by the userfinal_messages=&lt;String,bool&gt;{};final_textEditingController=TextEditingController();@overrideWidgetbuild(BuildContextcontext){returnScaffold(appBar:AppBar(title:constText('ChatGPT Demo'),),body:Column(children:[Expanded(child:ListView.builder(itemBuilder:(context,index){varisUserMessage=_messages.values.elementAt(index);returnRow(mainAxisAlignment:isUserMessage?MainAxisAlignment.end:MainAxisAlignment.start,children:[Flexible(child:Container(alignment:isUserMessage?Alignment.centerRight:Alignment.centerLeft,padding:constEdgeInsets.all(16),margin:EdgeInsets.only(top:4,bottom:4,left:isUserMessage?40:4,right:!isUserMessage?40:4,),decoration:BoxDecoration(borderRadius:BorderRadius.circular(8),color:isUserMessage?Colors.blue:Colors.grey,),child:Text(_messages.keys.elementAt(index)),),),],);},itemCount:_messages.length,),),TextField(controller:_textEditingController,onSubmitted:_sendMessage,decoration:InputDecoration(hintText:'Type your message',contentPadding:constEdgeInsets.all(8),suffixIcon:IconButton(icon:constIcon(Icons.send),onPressed:()=&gt;_sendMessage(_textEditingController.text),),),),],),);}void_sendMessage(Stringmessage)async{setState((){_messages[message]=true;_messages["..."]=false;});// Send API request to ChatGPTfinalresponse=awaithttp.post(Uri.parse('https://api.openai.com/v1/chat/completions'),headers:{'Authorization':'Bearer$openAiKey','Content-Type':'application/json',},body:jsonEncode(&lt;String,dynamic&gt;{'model':'gpt-3.5-turbo',"messages":[{"role":"user","content":message}]}),);if(response.statusCode==200){finaljson=jsonDecode(response.body);setState((){_messages.remove("...");_messages[json['choices'][0]['message']['content']]=false;});}else{print('Request failed with status:${response.statusCode}.');}// Clear text field_textEditingController.clear();}}</code></deckgo-highlight-code>1.Modifyyour`main.dart`filetodisplaythe`ChatPage`whentheappstarts.<deckgo-highlight-codelanguage="dart"theme="material"line-numbers="true"><codeslot="code">finalopenAiKey=dotenv.env['OPENAI_API_KEY'];voidmain()async{awaitdotenv.load();runApp(MyApp());}classMyAppextendsStatelessWidget{@overrideWidgetbuild(BuildContextcontext){returnMaterialApp(title:'ChatGPT Demo',home:ChatPage(),);}}
Enter fullscreen modeExit fullscreen mode

That's it! You now have a fully functional ChatGPT application built with Flutter. Launch your app and start chatting with ChatGPT.

ChatGPT App Demo


For suggestions and queries, justcontact me.

Top comments(0)

Subscribe
pic
Create template

Templates let you quickly answer FAQs or store snippets for re-use.

Dismiss

Are you sure you want to hide this comment? It will become hidden in your post, but will still be visible via the comment'spermalink.

For further actions, you may consider blocking this person and/orreporting abuse

Engineer by day. Batman by night.
  • Location
    Karachi, Pakistan
  • Education
    Bachelors in Computer Science
  • Work
    Freelance Mobile Application Developer
  • Joined

More fromZuhaib Ahmad

DEV Community

We're a place where coders share, stay up-to-date and grow their careers.

Log in Create account

[8]ページ先頭

©2009-2025 Movatter.jp