Flutter and chatgpt integration

import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
import 'package:bubble/bubble.dart';

void main() => runApp(MyApp());

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

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

class _ChatBotScreenState extends State<ChatBotScreen> {
  final messageInsert = TextEditingController();
  List<Map<String, dynamic>> messages = [];
  bool isDarkMode = true;

  Future<String> getChatGPTResponse(String message) async {
  try {
    final response = await http.post(
     
      headers: {
        'Content-Type': 'application/json',
        'Authorization': 'Bearer ■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■x1KHOhrL',
      },
      body: jsonEncode({
        'prompt': message,
        'max_tokens': 150,
      }),
    );

    if (response.statusCode == 200) {
      final Map<String, dynamic> data = json.decode(response.body);
      return data['choices'][0]['text'].toString();
    } else {
      print('Failed to load response. Status code: ${response.statusCode}');
      print('Response body: ${response.body}');
      throw Exception('Failed to load response');
    }
  } catch (error) {
    print('Error: $error');
    throw Exception('Failed to load response');
  }
}


  void response(query) async {
    String chatGPTResponse = await getChatGPTResponse(query);
    setState(() {
      messages.insert(0, {"data": 0, "message": chatGPTResponse});
    });
  }

  void deleteConversation() {
    setState(() {
      messages.clear();
    });
  }

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      debugShowCheckedModeBanner: false,
      theme: ThemeData(
        brightness: isDarkMode ? Brightness.dark : Brightness.light,
      ),
      home: Scaffold(
        appBar: AppBar(
          centerTitle: true,
          title: Text("MindMate AI Assistant"),
          actions: [
            Padding(
              padding: const EdgeInsets.all(8.0),
              child: Switch(
                value: isDarkMode,
                onChanged: (value) {
                  setState(() {
                    isDarkMode = value;
                  });
                },
              ),
            ),
          ],
          leading: IconButton(
            icon: Icon(Icons.delete),
            onPressed: () {
              showDialog(
                context: context,
                builder: (BuildContext context) {
                  return AlertDialog(
                    title: Text("Delete Conversation?"),
                    content: Text("Are you sure you want to delete the entire conversation?"),
                    actions: [
                      TextButton(
                        child: Text("CANCEL"),
                        onPressed: () {
                          Navigator.of(context).pop();
                        },
                      ),
                      TextButton(
                        child: Text("DELETE"),
                        onPressed: () {
                          deleteConversation();
                          Navigator.of(context).pop();
                        },
                      ),
                    ],
                  );
                },
              );
            },
          ),
        ),
        body: Container(
          child: Column(
            children: <Widget>[
              Flexible(
                child: ListView.builder(
                  reverse: true,
                  itemCount: messages.length,
                  itemBuilder: (context, index) => chat(
                    messages[index]["message"].toString(),
                    messages[index]["data"],
                    index,
                  ),
                ),
              ),
              Divider(
                height: 6.0,
              ),
              Container(
                padding: EdgeInsets.only(left: 15.0, right: 15.0, bottom: 20),
                margin: const EdgeInsets.symmetric(horizontal: 8.0),
                child: Row(
                  children: <Widget>[
                    Flexible(
                      child: TextField(
                        controller: messageInsert,
                        decoration: InputDecoration.collapsed(
                          hintText: "Send your message",
                          hintStyle: TextStyle(
                            fontWeight: FontWeight.bold,
                            fontSize: 18.0,
                          ),
                        ),
                      ),
                    ),
                    Container(
                      margin: EdgeInsets.symmetric(horizontal: 4.0),
                      child: IconButton(
                        icon: Icon(
                          Icons.send,
                          size: 30.0,
                        ),
                        onPressed: () {
                          if (messageInsert.text.isEmpty) {
                            print("empty message");
                          } else {
                            setState(() {
                              messages.insert(0, {
                                "data": 1,
                                "message": messageInsert.text,
                              });
                            });
                            response(messageInsert.text);
                            messageInsert.clear();
                          }
                        },
                      ),
                    ),
                  ],
                ),
              ),
              SizedBox(
                height: 15.0,
              ),
            ],
          ),
        ),
      ),
    );
  }

  Widget chat(String message, int data, int index) {
    return GestureDetector(
      onLongPress: () {
        showDialog(
          context: context,
          builder: (BuildContext context) {
            return AlertDialog(
              title: Text("Delete Message?"),
              content: Text("Are you sure you want to delete this message?"),
              actions: [
                TextButton(
                  child: Text("CANCEL"),
                  onPressed: () {
                    Navigator.of(context).pop();
                  },
                ),
                TextButton(
                  child: Text("DELETE"),
                  onPressed: () {
                    deleteMessage(index);
                    Navigator.of(context).pop();
                  },
                ),
              ],
            );
          },
        );
      },
      child: Padding(
        padding: EdgeInsets.all(10.0),
        child: Bubble(
          radius: Radius.circular(15.0),
          color: data == 0 ? Colors.blue : Colors.orangeAccent,
          elevation: 0.0,
          alignment:
              data == 0 ? Alignment.topLeft : Alignment.topRight,
          nip: data == 0
              ? BubbleNip.leftBottom
              : BubbleNip.rightTop,
          child: Padding(
            padding: EdgeInsets.all(2.0),
            child: Row(
              mainAxisSize: MainAxisSize.min,
              children: <Widget>[
                CircleAvatar(
                  backgroundImage: AssetImage(
                    data == 0 ? "assets/images/bot.png" : "assets/images/bot.png",
                  ),
                ),
                SizedBox(
                  width: 10.0,
                ),
                Flexible(
                  child: Text(
                    message,
                    style: TextStyle(
                      color: Colors.white,
                      fontWeight: FontWeight.bold,
                    ),
                  ),
                ),
              ],
            ),
          ),
        ),
      ),
    );
  }

  void deleteMessage(int index) {
    setState(() {
      messages.removeAt(index);
    });
  }
}

I CAN TYPE A QUESTION AND NO RESPONSE

Welcome to the developer forum.

It would help if you format your code correctly.

Are you getting an error message?