Flutter Chat App with ChatGPT API Integration
This code snippet showcases a Flutter chat application integrated with ChatGPT API, enabling real-time conversations with a chatbot. The app uses the ChatView package for its chat interface and Dio for handling HTTP requests to the ChatGPT API. User input is captured and sent to the API via POST requests, and the chatbot's response is received and displayed in the chat interface. This example demonstrates the functionality of interacting with ChatGPT API in a Flutter application, providing a foundation for building more complex chat applications.
import 'package:flutter/material.dart';
import 'package:chatview/chatview.dart';
import 'package:dio/dio.dart';
class chatgpt extends StatefulWidget {
@override
_chatgptState createState() => _chatgptState();
}
List<Message> messageList = [
Message(
id: '1',
message: 'Hi',
createdAt: DateTime.now(),
sendBy: '2',
),
Message(
id: '2',
message: 'Hello',
createdAt: DateTime.now(),
sendBy: '1',
),
];
class _chatgptState extends State<chatgpt> {
final chatController = ChatController(
initialMessageList: messageList,
scrollController: ScrollController(),
);
void onSendTap(String message, ReplyMessage replyMessage) async {
final newMessage = Message(
id: '3',
message: message,
createdAt: DateTime.now(),
sendBy: '1',
);
chatController.addMessage(newMessage);
try {
final dio = Dio();
final response = await dio.post(
'https://chatgpt-chatpt-zggoappkts.cn-beijing.fcapp.run',
data: {'message': message},
);
final botMessage = Message(
id: '4',
message: response.data['message'],
createdAt: DateTime.now(),
sendBy: '2',
);
chatController.addMessage(botMessage);
} catch (e) {
print(e);
}
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Chat'),
),
body: ChatView(
sender: ChatUser(id: '1', name: 'Flutter'),
receiver: ChatUser(id: '2', name: 'Simform'),
chatController: chatController,
onSendTap: onSendTap,
));
}
}
The provided code demonstrates a basic implementation of capturing user messages in a Flutter chat app and sending them to a ChatGPT API endpoint for processing. The application leverages the ChatView package for chat interface management, utilizes Dio to handle HTTP requests, and integrates with the ChatGPT API to receive bot responses. The code also implements error handling using a try-catch block, ensuring the app remains stable even if the API request fails. This example serves as a starting point for building more elaborate chat applications that interact with ChatGPT API or other similar services.
原文地址: https://www.cveoy.top/t/topic/lIKP 著作权归作者所有。请勿转载和采集!