|
- /*
- AI测试场景
- */
- import 'package:flutter/material.dart';
- import 'package:demo001/doubao/DouBao.dart';
-
- class ChatItem {
- String msg = "";
- int state = 0;
-
- ChatItem({required this.msg});
-
- void append(String _msg) {
- msg += _msg;
- }
-
- void end() {
- state = 1;
- }
- }
-
- class AIChatScene extends StatefulWidget {
- @override
- _AIChatSceneState createState() => _AIChatSceneState();
- }
-
- class _AIChatSceneState extends State<AIChatScene> {
- // final String apiKey = "sk-3adfd188a3134e718bbf704f525aff17";
- final Doubao doubao = Doubao(
- apiKey: "418ec475-e2dc-4b76-8aca-842d81bc3466",
- modelId: "ep-20250203161136-9lrxg");
-
- final List<ChatItem> _chats = [ChatItem(msg: "我是测试代码")];
- ChatItem? _currchat;
- final TextEditingController _textController = TextEditingController();
-
- //发送消息
- _sendMessage() async {
- _currchat = ChatItem(msg: "");
- setState(() {
- _chats.add(_currchat!);
- });
- var stream = doubao.chat(_textController.text);
- _textController.text = "";
- await for (final content in stream) {
- setState(() {
- _currchat?.append(content);
- });
- print('实时更新: $content');
- }
- print('结束恢复');
- _currchat?.end();
- }
-
- @override
- Widget build(BuildContext context) {
- return Scaffold(
- appBar: AppBar(title: Text("AI测试")),
- body: ListView.builder(
- itemCount: _chats.length,
- itemBuilder: (context, index) {
- var item = _chats[index];
- return _buildAudioMessage(item);
- },
- ),
- bottomNavigationBar: Padding(
- padding: const EdgeInsets.all(20.0),
- child: Container(
- decoration: BoxDecoration(
- color: Colors.grey[200], // 背景颜色
- borderRadius: BorderRadius.circular(30), // 圆角
- ),
- padding: EdgeInsets.symmetric(
- horizontal: 20, vertical: 10), // 输入框和按钮的内边距
- child: Row(
- children: [
- Expanded(
- child: TextField(
- controller: _textController, // 用于获取输入的文本
- decoration: InputDecoration(
- hintText: '输入消息...', // 提示文本
- border: InputBorder.none, // 去除默认边框
- contentPadding:
- EdgeInsets.symmetric(vertical: 12), // 调整内边距
- ),
- ),
- ),
- IconButton(
- icon: Icon(Icons.send, color: Colors.blue), // 发送按钮图标
- onPressed: _sendMessage, // 发送按钮点击事件
- ),
- ],
- ),
- ),
- ));
- }
-
- // 构建语音消息
- Widget _buildAudioMessage(ChatItem data) {
- return Padding(
- padding: const EdgeInsets.symmetric(vertical: 10, horizontal: 15),
- child: Column(
- crossAxisAlignment: CrossAxisAlignment.start,
- children: [
- // 音频播放按钮
- GestureDetector(
- onTap: () {},
- child: Container(
- padding: EdgeInsets.symmetric(vertical: 10, horizontal: 20),
- decoration: BoxDecoration(
- color: Colors.green,
- borderRadius: BorderRadius.circular(30),
- ),
- child: Row(
- children: [
- Text(
- data.msg,
- style: TextStyle(color: Colors.white),
- ),
- ],
- ),
- ),
- ),
- SizedBox(height: 5),
- ],
- ),
- );
- }
- }
|