Mega Bundle SALE is ON! Get ALL of our amazing Flutter codebases with 95% OFF discount 🔥

This tutorial provides a step-by-step guide on how to integrate OpenAI’s ChatGPT API into a Flutter application. We will start with setting up a Flutter project, then we will integrate the ChatGPT API.

Flutter ChatGPT OpenAI

Table of Contents

  1. Prerequisites
  2. Setting Up Your Flutter Project
  3. Adding Dependencies
  4. Creating the ChatGPT API Service
  5. Building the Chat Interface
  6. Connecting the Interface to the ChatGPT Service

Prerequisites

Before starting, make sure you have:

  1. Flutter and Dart installed on your system. If not, you can download and install them from here.
  2. An IDE installed, such as VS Code or Android Studio.
  3. Basic knowledge of Flutter and Dart.
  4. An OpenAI API key. You can get one from the OpenAI dashboard.

Setting Up Your Flutter Project

Start by creating a new Flutter project:

flutter create chat_gpt_app

Move into your new project’s directory:

cd chat_gpt_app

Adding Dependencies

We will be using http for making HTTP requests to the ChatGPT API and dotenv for handling environment variables (such as the OpenAI API key). Add these dependencies to your pubspec.yaml file:

dependencies:
  flutter:
    sdk: flutter
  http: ^0.13.3
  flutter_dotenv: ^5.0.0

Then run flutter pub get to install the dependencies.

Now, create a .env file in the root directory of your project and add your OpenAI API key:

OPENAI_KEY=your_api_key_here

Make sure you load the environment variables at the start of your application. Modify the main.dart file to include:

import 'package:flutter_dotenv/flutter_dotenv.dart' as dotenv;

void main() async {
  await dotenv.load();
  runApp(MyApp());
}

Creating the ChatGPT API Service

Create a new file named chat_gpt_service.dart in your lib directory, and write the following code:

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

class ChatGPTService {
  final String _apiUrl = 'https://api.openai.com/v1/engines/davinci-codex/completions';
  final String _apiKey = dotenv.env['OPENAI_KEY']!;

  Future<String> getResponse(String message) async {
    final response = await http.post(
      Uri.parse(_apiUrl),
      headers: {
        'Content-Type': 'application/json',
        'Authorization': 'Bearer $_apiKey'
      },
      body: jsonEncode({
        'prompt': message,
        'max_tokens': 60
      })
    );

    if (response.statusCode == 200) {
      return jsonDecode(response.body)['choices'][0]['text'];
    } else {
      throw Exception('Failed to load response');
    }
  }
}

Building the Chat Interface

This tutorial doesn’t focus on creating a sophisticated UI, so for brevity, we’ll create a simple chat interface with a TextField for the user input and a FloatingActionButton for sending messages.

In your main.dart file, replace the existing code with:

import 'package:flutter/material.dart';

void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: ChatScreen(),
    );
  }
}

class ChatScreen extends StatefulWidget {
  @override
  _ChatScreenState createState() => _ChatScreenState();
}

class _ChatScreenState extends State<ChatScreen> {
  final List<String> _messages = [];
  final TextEditingController _textController = TextEditingController();

  void _handleSubmitted(String text) {
    // Logic to send message will go here
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: Text('ChatGPT')),
      body: Column(
        children: [
          Expanded(
            child: ListView.builder(
              itemCount: _messages.length,
              itemBuilder: (context, index) => ListTile(title: Text(_messages[index])),
            ),
          ),
          Container(
            margin: const EdgeInsets.symmetric(horizontal: 8.0),
            child: Row(
              children: [
                Expanded(
                  child: TextField(
                    controller: _textController,
                    decoration: InputDecoration(hintText: 'Send a message'),
                  ),
                ),
                FloatingActionButton(
                  onPressed: () => _handleSubmitted(_textController.text),
                  child: Icon(Icons.send),
                ),
              ],
            ),
          ),
        ],
      ),
    );
  }
}

Connecting the Interface to the ChatGPT Service

Finally, we need to connect our chat interface with the ChatGPT service. Modify the _handleSubmitted function in the ChatScreen widget to:

import 'chat_gpt_service.dart';

// ...previous code

void _handleSubmitted(String text) async {
  if (text.isEmpty) return;

  _textController.clear();
  setState(() {
    _messages.add('User: $text');
  });

  final String response = await ChatGPTService().getResponse(text);
  setState(() {
    _messages.add('ChatGPT: $response');
  });
}

That’s it! You now have a Flutter application integrated with the ChatGPT API. To start the app, run flutter run in your terminal.

Remember to keep your API key secure and do not expose it in a real-world application. It’s recommended to set up a backend server that communicates with the OpenAI API, and your Flutter app should communicate with this server.

If you are looking for the same integration, but in React Native, check out our company’s React Native ChatGPT app template.

Categories: Flutter Tutorials

Leave a Reply

Your email address will not be published. Required fields are marked *

Shopping Cart