我正在尝试使用 open ai API 制作一个应用程序。当我第一次发送请求时,它会显示结果。但第二次并没有改变结果。但重启后就正常了。我如何解决它?是否存在状态更新问题?我只是为了练习而做的。所以我这里没有做任何设计。只是用了逻辑
import 'package:flutter/material.dart';
import 'package:flutter_application_2/api-service/ApiModel.dart';
import 'package:flutter_application_2/api-service/service.dart';
import 'package:flutter_spinkit/flutter_spinkit.dart';
import 'package:animated_text_kit/animated_text_kit.dart';
void main() {
runApp(MyApp());
}
class MyApp extends StatefulWidget {
@override
State<MyApp> createState() => _MyAppState();
}
class _MyAppState extends State<MyApp> {
bool isTyping = false;
TextEditingController textController = TextEditingController();
ApiClass apiObj = ApiClass();
List<ApiModel> chatList = [];
@override
Widget build(BuildContext context) {
return MaterialApp(
title: "Chat GPT",
theme: ThemeData(
textSelectionTheme:
TextSelectionThemeData(selectionHandleColor: Colors.transparent)),
home: Scaffold(
appBar: PreferredSize(
preferredSize: Size.fromHeight(50),
child: AppBar(
title: Text("AI ChatBot"),
),
),
body: Column(
children: [
Text(textController.text),
Expanded(
child: ListView.builder(
itemCount: chatList.length,
itemBuilder: (context, index) {
return AnimatedTextKit(
animatedTexts: [
TypewriterAnimatedText(
chatList[index].message!.content.toString(),
speed: Duration(milliseconds: 50))
],
totalRepeatCount: 1,
);
},
),
),
if (isTyping) ...[
SpinKitThreeBounce(
size: 18,
color: Colors.grey,
)
],
TextField(
controller: textController,
decoration: InputDecoration(
contentPadding: EdgeInsets.symmetric(horizontal: 10),
hintText: "Type your question here...",
suffixIcon: IconButton(
onPressed: () async {
setState(() {
isTyping = true;
});
chatList = await apiObj.sentData(textController.text);
setState(() {
isTyping = false;
});
},
icon: Icon(Icons.send)),
filled: true,
fillColor: Colors.grey,
border: InputBorder.none,
),
textAlignVertical: TextAlignVertical.center,
style: TextStyle(color: Colors.white),
cursorColor: Colors.amber,
)
],
),
),
);
}
}
API服务代码:
import 'dart:convert';
import 'package:http/http.dart';
import 'ApiModel.dart';
class ApiClass {
Future<List<ApiModel>> sentData(msg) async {
Response response =
await post(Uri.parse('https://api.openai.com/v1/chat/completions'),
headers: {
'Authorization': 'Bearer $ApiCode',
'Content-Type': 'application/json'
},
body: jsonEncode({
"model": "gpt-3.5-turbo",
"messages": [
{"role": "user", "content": msg.toString()}
],
"temperature": 0.7
}));
Map<String,dynamic>json = jsonDecode(response.body);
List<dynamic> jsonData = json['choices'];
List<ApiModel> sendChat =
jsonData.map((e) => ApiModel.fromJson(e)).toList();
return sendChat;
}
}
我没有看到状态问题。我只是简化了用户界面,使其完全独立。也许问题出在 AnimatedTypedText 上。我将尝试使用它来看看这是否会带来问题。
import 'package:flutter/material.dart';
import 'package:http/http.dart';
class ApiModel {
const ApiModel(this.message);
final String message;
}
const apiKey = 'YOUR_OPEN_AI_SECRET_API_KEY' ;
class ApiClass {
Future<List<ApiModel>> sentData(msg) async {
Response response = await post(Uri.parse('https://api.openai.com/v1/chat/completions'),
headers: {'Authorization': 'Bearer $apiKey', 'Content-Type': 'application/json'},
body: jsonEncode({
"model": "gpt-3.5-turbo",
"messages": [
{"role": "user", "content": msg.toString()}
],
"temperature": 0.7
}));
return [ApiModel(response.body)];
}
}
void main() {
runApp(MyApp());
}
class MyApp extends StatefulWidget {
@override
State<MyApp> createState() => _MyAppState();
}
class _MyAppState extends State<MyApp> {
bool isTyping = false;
TextEditingController textController = TextEditingController();
ApiClass apiObj = ApiClass();
List<ApiModel> chatList = [];
@override
Widget build(BuildContext context) {
return MaterialApp(
title: "Chat GPT",
theme: ThemeData(textSelectionTheme: const TextSelectionThemeData(selectionHandleColor: Colors.transparent)),
home: Scaffold(
appBar: PreferredSize(
preferredSize: const Size.fromHeight(50),
child: AppBar(
title: const Text("AI ChatBot"),
),
),
body: Column(
children: [
Text(textController.text),
Expanded(
child: ListView.builder(
itemCount: chatList.length,
itemBuilder: (context, index) {
return Text(
chatList[index].message,
);
},
),
),
if (isTyping) const CircularProgressIndicator(),
TextField(
controller: textController,
decoration: InputDecoration(
contentPadding: const EdgeInsets.symmetric(horizontal: 10),
hintText: "Type your question here...",
suffixIcon: IconButton(
onPressed: () async {
setState(() {
isTyping = true;
});
chatList = await apiObj.sentData(textController.text);
setState(() {
isTyping = false;
});
},
icon: const Icon(Icons.send)),
filled: true,
fillColor: Colors.grey,
border: InputBorder.none,
),
textAlignVertical: TextAlignVertical.center,
style: const TextStyle(color: Colors.white),
cursorColor: Colors.amber,
)
],
),
),
);
}
}