How to use ChatGPT in Flutter? This is Basic Example

Flutter is a powerful framework for building cross-platform mobile applications, while ChatGPT is a cutting-edge natural language processing tool that can help you build intelligent chatbots, language translators, and more. By integrating the ChatGPT API with your Flutter app, you can create an intelligent chatbot that can understand natural language and respond appropriately.

In this tutorial, we will guide you through the steps of integrating ChatGPT API with your Flutter app. You will need to have some knowledge of Flutter and the Dart programming language to follow along.

Step 1: Create a ChatGPT Account

Before we begin, you need to create a ChatGPT account. Go to the ChatGPT website and sign up for a free account. Once you have an account, you will be able to access your API key, which you will need to use the ChatGPT API.

Step 2: Add the http package to your Flutter project

To make HTTP requests to the ChatGPT API from your Flutter app, you need to add the http package to your project. To do this, open your pubspec.yaml file and add the following line to the dependencies section:


Then, run the following command to install the package:

flutter pub get

Step 3: Make API Requests to ChatGPT

To make requests to the ChatGPT API, you need to use the http package we added in step 2. The ChatGPT API provides a simple HTTP endpoint for sending text and receiving a response in JSON format.

Here’s an example of how to send a text to ChatGPT and receive a response using the http package:

import 'package:http/http.dart' as http;
import 'dart:convert';

final apiKey = 'your_api_key_here';
final apiUrl = '';

Future<String> getChatGPTResponse(String text) async {
  final response = await,
      headers: {'Content-Type': 'application/json', 'Authorization': 'Bearer $apiKey'},
      body: jsonEncode({
        'prompt': '$text\n',
        'temperature': 0.5,
        'max_tokens': 60,
        'n': 1,
        'stop': '\n',

  if (response.statusCode == 200) {
    final data = jsonDecode(response.body);
    final responseText = data['choices'][0]['text'];
    return responseText;
  } else {
    throw Exception('Failed to get response from ChatGPT API');

In the example above, we defined a function called getChatGPTResponse that takes a text input and sends an HTTP POST request to the ChatGPT API. We pass our API key in the request headers, and the text input in the request body. We also specify some parameters to control the response we receive from the API, such as temperature, max_tokens, n, and stop.

The function returns the response text received from the API. If the request fails, an exception is thrown.

Step 4: Use the ChatGPT API in your Flutter app

Now that we have a function that can send requests to the ChatGPT API, we can use it in our Flutter app. Here’s an example of how to use the getChatGPTResponse function in a simple chatbot app:

import 'package:flutter/material.dart';
import 'chat_gpt_api.dart';

class ChatBotScreen extends StatefulWidget {
  _ChatBotScreenState createState() => _ChatBotScreenState();

class _ChatBotScreenState extends State<ChatBotScreen> {
  final TextEditingController _controller = TextEditingController();
  List<String> _messages = [];

  void _sendMessage(String text) {
    setState(() {
      _messages.add('User: $text');

    getChatGPTResponse(text).then((response) {
      setState(() {
        _messages.add('ChatBot: $response');
    }).catchError((error) {
      setState(() {
        _messages.add('Error: $error');


  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('ChatBot'),
      body: Column(
        children: <Widget>[
            child: ListView.builder(
              itemBuilder: (context, index) {
                if (index < _messages.length) {
                  return ListTile(
                    title: Text(_messages[index]),
                return null;
          Divider(height: 1.0),
            decoration: BoxDecoration(color: Theme.of(context).cardColor),
            child: Row(
              children: <Widget>[
                  child: TextField(
                    controller: _controller,
                    onSubmitted: _sendMessage,
                        InputDecoration.collapsed(hintText: 'Send a message'),
                  icon: Icon(Icons.send),
                  onPressed: () => _sendMessage(_controller.text),

In the example above, we defined a ChatBotScreen widget that displays a list of messages and a text input for sending messages. When the user enters a message and taps the send button, the _sendMessage function is called, which sends the message to the ChatGPT API and adds the user’s message and the response to the list of messages.

To display the list of messages, we use a ListView.builder widget that builds a ListTile for each message. The text input and send button are contained in a Row widget.


By following the steps outlined in this tutorial, you should now have a basic understanding of how to integrate the ChatGPT API with your Flutter app to create an intelligent chatbot. Remember to use your API key in your requests, and to adjust the parameters as needed to control the response you receive from the API.

With the power of Flutter and ChatGPT, you can build advanced chatbots that can understand natural language, translate languages, and more. Good luck with your project!

Related posts:

  1. OpenAI in Flutter: Advanced Examples of Using Text Completion
  2. Advanced sqflite Techniques in Flutter: Error handling
  3. How to use cupertino_icons?