提交 28ae4749 authored 作者: songchuancai's avatar songchuancai

增加应用列表

上级 e92fe5f9
import 'package:allen/pallete.dart'; import 'package:allen/pallete.dart';
import 'package:animate_do/animate_do.dart';
import 'package:animate_do/animate_do.dart'; import 'package:flutter/material.dart';
import 'package:flutter_tts/flutter_tts.dart';
import 'package:flutter/material.dart'; import 'package:speech_to_text/speech_recognition_result.dart';
import 'package:speech_to_text/speech_to_text.dart';
import 'package:flutter_tts/flutter_tts.dart'; import 'package:flutter/foundation.dart' show kIsWeb;
import 'package:uuid/uuid.dart';
import 'package:speech_to_text/speech_recognition_result.dart'; import 'models/conversation.dart';
import 'services/storage_service.dart';
import 'package:speech_to_text/speech_to_text.dart'; import 'services/chat_service.dart';
import 'models/chat_message.dart';
import 'package:flutter/foundation.dart' show kIsWeb; import 'models/user.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:uuid/uuid.dart'; import 'package:flutter_markdown/flutter_markdown.dart';
import 'pages/apps_page.dart';
import 'models/conversation.dart'; class HomePage extends StatefulWidget {
final String? customTitle;
final String? customDescription;
import 'services/storage_service.dart';
final String? customImageUrl;
final bool hideNavigation;
import 'services/chat_service.dart';
const HomePage({
super.key,
this.customTitle,
import 'models/chat_message.dart'; this.customDescription,
this.customImageUrl,
this.hideNavigation = false,
});
import 'models/user.dart';
@override
State<HomePage> createState() => _HomePageState();
}
import 'package:shared_preferences/shared_preferences.dart';
class _HomePageState extends State<HomePage> {
final speechToText = SpeechToText();
import 'package:flutter_markdown/flutter_markdown.dart'; final flutterTts = FlutterTts();
String lastWords = '';
import 'pages/apps_page.dart'; final OpenAIService openAIService = OpenAIService();
String? generatedContent;
String? generatedImageUrl;
int start = 200;
class HomePage extends StatefulWidget { int delay = 200;
final TextEditingController _messageController = TextEditingController();
final String? customTitle; String currentStreamedContent = '';
List<ChatMessage> messages = [];
final String? customDescription; bool _isLoading = false;
bool _isVoiceMode = true;
final String? customImageUrl; bool _isListeningPressed = false;
String _currentVoiceText = '';
final bool hideNavigation; late StorageService _storageService;
late SharedPreferences _prefs;
late Conversation _currentConversation;
List<Conversation> _conversations = [];
const HomePage({ int _currentIndex = 0;
@override
void initState() {
super.key, super.initState();
_initializeStorage();
this.customTitle, initSpeechToText();
_initTts();
}
this.customDescription,
Future<void> _initializeStorage() async {
_prefs = await SharedPreferences.getInstance();
this.customImageUrl, _storageService = StorageService(_prefs);
_conversations = await _storageService.getConversations();
this.hideNavigation = false, if (_conversations.isEmpty) {
_createNewConversation();
} else {
_currentConversation = _conversations.first;
});
setState(() {
messages = _currentConversation.messages;
});
}
}
Future<void> _createNewConversation() async {
@override final newConversation = Conversation(
id: const Uuid().v4(),
title: '新会话 ${_conversations.length + 1}',
createdAt: DateTime.now(),
State<HomePage> createState() => _HomePageState(); messages: [],
);
await _storageService.addConversation(newConversation);
}
setState(() {
_conversations.insert(0, newConversation);
_currentConversation = newConversation;
messages = [];
});
class _HomePageState extends State<HomePage> { }
Future<void> _updateCurrentConversation() async {
_currentConversation = Conversation(
final speechToText = SpeechToText(); id: _currentConversation.id,
title: _currentConversation.title,
createdAt: _currentConversation.createdAt,
messages: messages,
final flutterTts = FlutterTts(); );
await _storageService.updateConversation(_currentConversation);
}
String lastWords = '';
Future<void> _initTts() async {
if (!kIsWeb) {
await flutterTts.setSharedInstance(true);
final OpenAIService openAIService = OpenAIService(); }
setState(() {});
}
String? generatedContent;
Future<void> initSpeechToText() async {
await speechToText.initialize();
String? generatedImageUrl; setState(() {});
}
Future<void> startListening() async {
int start = 200; await speechToText.listen(onResult: onSpeechResult);
setState(() {});
}
int delay = 200;
Future<void> stopListening() async {
await speechToText.stop();
final TextEditingController _messageController = TextEditingController(); setState(() {});
}
Future<void> onSpeechResult(SpeechRecognitionResult result) async {
String currentStreamedContent = ''; setState(() {
lastWords = result.recognizedWords;
_currentVoiceText = result.recognizedWords;
List<ChatMessage> messages = []; });
}
Future<void> systemSpeak(String content) async {
bool _isLoading = false; try {
if (kIsWeb) {
// 设置语速
bool _isVoiceMode = true; await flutterTts.setSpeechRate(3);
// 音调
bool _isListeningPressed = false; await flutterTts.setPitch(0.8);
await flutterTts.speak(content);
} else {
String _currentVoiceText = ''; await flutterTts.setSharedInstance(true);
await flutterTts.speak(content);
}
late StorageService _storageService; } catch (e) {
print('TTS Error: $e');
}
}
late SharedPreferences _prefs;
Future<void> _sendMessage() async {
if (!mounted) return; // 添加这行
late Conversation _currentConversation; if (_messageController.text.isEmpty) return;
String userMessage = _messageController.text;
List<Conversation> _conversations = []; _messageController.clear();
setState(() {
messages.add(ChatMessage(
int _currentIndex = 0; text: userMessage,
isUserMessage: true,
));
currentStreamedContent = '';
_isLoading = true;
});
@override
try {
String fullResponse = '';
void initState() { bool isFirstChunk = true;
// 创建一个缓冲区来存储收到的文本
super.initState(); StringBuffer buffer = StringBuffer();
await for (final chunk in openAIService.chatGPTAPI(userMessage)) {
buffer.write(chunk);
_initializeStorage();
// 逐字显示文本
for (int i = fullResponse.length; i < buffer.length; i++) {
initSpeechToText(); setState(() {
fullResponse += buffer.toString()[i];
if (isFirstChunk && i == 0) {
_initTts(); messages.add(ChatMessage(
text: fullResponse,
isUserMessage: false,
));
}
isFirstChunk = false;
} else {
messages.last = ChatMessage(
text: fullResponse,
isUserMessage: false,
);
}
Future<void> _initializeStorage() async { });
// 添加短暂延迟以创建打字效果
_prefs = await SharedPreferences.getInstance(); await Future.delayed(const Duration(milliseconds: 50));
}
}
_storageService = StorageService(_prefs); await systemSpeak(fullResponse);
await _updateCurrentConversation();
} catch (e) {
_conversations = await _storageService.getConversations(); setState(() {
messages.add(ChatMessage(
text: '抱歉,出现了一些错误:$e',
isUserMessage: false,
if (_conversations.isEmpty) { ));
});
} finally {
setState(() {
_createNewConversation(); _isLoading = false;
});
}
}
} else {
Future<void> _processAIResponse(String userInput) async {
try {
String fullResponse = '';
_currentConversation = _conversations.first;
bool isFirstChunk = true;
// 创建一个缓冲区来储收到的文本
setState(() {
StringBuffer buffer = StringBuffer();
await for (final chunk in openAIService.chatGPTAPI(userInput)) {
messages = _currentConversation.messages; buffer.write(chunk);
// 逐字显示文本
}); for (int i = fullResponse.length; i < buffer.length; i++) {
setState(() {
fullResponse += buffer.toString()[i];
} if (isFirstChunk && i == 0) {
messages.add(ChatMessage(
text: fullResponse,
isUserMessage: false,
} ));
isFirstChunk = false;
} else {
messages.last = ChatMessage(
text: fullResponse,
isUserMessage: false,
);
Future<void> _createNewConversation() async { }
});
// 添加短暂延迟以创建打字效果
final newConversation = Conversation(
await Future.delayed(const Duration(milliseconds: 50));
}
}
id: const Uuid().v4(),
await systemSpeak(fullResponse);
await _updateCurrentConversation();
title: '新会话 ${_conversations.length + 1}', } catch (e) {
setState(() {
messages.add(ChatMessage(
text: '抱歉,出现了一些错误:$e',
createdAt: DateTime.now(), isUserMessage: false,
));
});
} finally {
messages: [], setState(() {
_isLoading = false;
});
}
); }
@override
void dispose() {
super.dispose();
speechToText.stop();
await _storageService.addConversation(newConversation); flutterTts.stop();
_messageController.dispose();
}
setState(() {
Widget _buildBottomInput() {
return Container(
padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 8),
_conversations.insert(0, newConversation); decoration: BoxDecoration(
color: Colors.white,
boxShadow: [
BoxShadow(
_currentConversation = newConversation; color: Colors.grey.withOpacity(0.1),
spreadRadius: 1,
blurRadius: 3,
offset: const Offset(0, -1),
messages = []; ),
],
),
child: Row(
}); children: [
Expanded(
child: _isVoiceMode
? GestureDetector(
} onLongPressStart: (_) async {
setState(() {
_isListeningPressed = true;
_currentVoiceText = '';
});
await startListening();
Future<void> _updateCurrentConversation() async { },
onLongPressEnd: (_) async {
setState(() => _isListeningPressed = false);
_currentConversation = Conversation( await stopListening();
final finalVoiceText = _currentVoiceText;
id: _currentConversation.id, if (finalVoiceText.isNotEmpty) {
setState(() {
messages.add(ChatMessage(
text: finalVoiceText,
title: _currentConversation.title, isUserMessage: true,
));
_isLoading = true;
createdAt: _currentConversation.createdAt, });
await _processAIResponse(finalVoiceText);
}
messages: messages,
setState(() {
_currentVoiceText = '';
});
); },
child: Container(
padding: const EdgeInsets.symmetric(
horizontal: 20,
await _storageService.updateConversation(_currentConversation); vertical: 10,
),
decoration: BoxDecoration(
color: Colors.grey[100],
} borderRadius: BorderRadius.circular(25),
),
child: Text(
_isListeningPressed
? (_currentVoiceText.isEmpty
? '正在聆听...'
: _currentVoiceText)
: '按住说话',
Future<void> _initTts() async { textAlign: TextAlign.center,
style: TextStyle(
color: _isListeningPressed
? Pallete.firstSuggestionBoxColor
if (!kIsWeb) { : Colors.grey[600],
),
),
),
await flutterTts.setSharedInstance(true); )
: TextField(
controller: _messageController,
decoration: InputDecoration(
} hintText: '输入消息...',
border: OutlineInputBorder(
borderRadius: BorderRadius.circular(25),
borderSide: BorderSide.none,
setState(() {}); ),
filled: true,
fillColor: Colors.grey[100],
contentPadding: const EdgeInsets.symmetric(
} horizontal: 20,
vertical: 10,
),
),
),
),
const SizedBox(width: 8),
IconButton(
Future<void> initSpeechToText() async { icon: Icon(
_isVoiceMode ? Icons.keyboard : Icons.mic,
color: Pallete.firstSuggestionBoxColor,
),
await speechToText.initialize(); onPressed: () {
setState(() => _isVoiceMode = !_isVoiceMode);
},
),
setState(() {}); if (!_isVoiceMode)
IconButton(
icon: const Icon(
Icons.send,
} color: Pallete.firstSuggestionBoxColor,
),
onPressed: _sendMessage,
),
],
),
);
}
Future<void> startListening() async {
AppBar _buildAppBar() {
return AppBar(
title: Row(
await speechToText.listen(onResult: onSpeechResult); mainAxisAlignment: MainAxisAlignment.center,
children: [
TextButton(
onPressed: () {
setState(() {}); setState(() => _currentIndex = 0);
},
child: Text(
'对话',
} style: TextStyle(
fontSize: _currentIndex == 0 ? 20 : 16,
fontWeight:
_currentIndex == 0 ? FontWeight.bold : FontWeight.normal,
color: _currentIndex == 0
? Pallete.firstSuggestionBoxColor
: Colors.grey,
),
Future<void> stopListening() async { ),
),
const SizedBox(width: 20),
TextButton(
await speechToText.stop(); onPressed: () {
setState(() => _currentIndex = 1);
},
child: Text(
setState(() {}); '应用',
style: TextStyle(
fontSize: _currentIndex == 1 ? 20 : 16,
fontWeight:
} _currentIndex == 1 ? FontWeight.bold : FontWeight.normal,
color: _currentIndex == 1
? Pallete.firstSuggestionBoxColor
: Colors.grey,
),
),
),
],
Future<void> onSpeechResult(SpeechRecognitionResult result) async { ),
leading: Builder(
builder: (context) => IconButton(
icon: const Icon(Icons.menu),
setState(() { onPressed: () => Scaffold.of(context).openDrawer(),
),
),
);
lastWords = result.recognizedWords; }
Widget _buildDrawer(BuildContext context) {
return Drawer(
_currentVoiceText = result.recognizedWords; child: Column(
children: [
DrawerHeader(
decoration: BoxDecoration(
}); color: Pallete.firstSuggestionBoxColor,
),
child: const Center(
child: Text(
} '会话列表',
style: TextStyle(
color: Colors.white,
fontSize: 24,
),
),
),
),
Future<void> systemSpeak(String content) async { ListTile(
leading: const Icon(Icons.add),
title: const Text('新建会话'),
onTap: () {
try { _createNewConversation();
Navigator.pop(context);
},
if (kIsWeb) { ),
Expanded(
child: ListView.builder(
itemCount: _conversations.length,
// 设置语速 itemBuilder: (context, index) {
final conversation = _conversations[index];
return ListTile(
await flutterTts.setSpeechRate(3); leading: const Icon(Icons.chat),
title: Text(conversation.title),
subtitle: Text(
conversation.messages.isEmpty
// 音调 ? '暂无消息'
: conversation.messages.last.text,
maxLines: 1,
overflow: TextOverflow.ellipsis,
await flutterTts.setPitch(0.8); ),
selected: _currentConversation.id == conversation.id,
onTap: () {
setState(() {
await flutterTts.speak(content); _currentConversation = conversation;
messages = conversation.messages;
});
} else {
Navigator.pop(context);
},
trailing: IconButton(
await flutterTts.setSharedInstance(true); icon: const Icon(Icons.delete),
onPressed: () async {
await _storageService.deleteConversation(conversation.id);
await flutterTts.speak(content); setState(() {
_conversations.removeAt(index);
if (_currentConversation.id == conversation.id) {
} if (_conversations.isEmpty) {
_createNewConversation();
} else {
_currentConversation = _conversations.first;
} catch (e) {
messages = _currentConversation.messages;
}
}
print('TTS Error: $e'); });
},
),
);
} },
),
),
const Spacer(),
} const Divider(height: 1),
FutureBuilder<User?>(
future: StorageService.getUser(),
builder: (context, snapshot) {
if (!snapshot.hasData) return const SizedBox();
return Container(
padding: const EdgeInsets.all(16),
Future<void> _sendMessage() async { decoration: BoxDecoration(
color: Colors.grey[50],
),
child: Column(
if (_messageController.text.isEmpty) return; children: [
Row(
children: [
Container(
width: 50,
height: 50,
decoration: BoxDecoration(
color: Pallete.firstSuggestionBoxColor,
String userMessage = _messageController.text; shape: BoxShape.circle,
),
child: Center(
child: Text(
_messageController.clear(); snapshot.data!.username[0].toUpperCase(),
style: const TextStyle(
color: Colors.white,
fontSize: 24,
fontWeight: FontWeight.bold,
),
),
),
setState(() { ),
const SizedBox(width: 16),
Expanded(
child: Column(
messages.add(ChatMessage( crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
snapshot.data!.username,
text: userMessage, style: const TextStyle(
fontSize: 18,
fontWeight: FontWeight.bold,
),
isUserMessage: true, ),
const SizedBox(height: 4),
Text(
'在线',
)); style: TextStyle(
fontSize: 14,
color: Colors.green[600],
),
currentStreamedContent = ''; ),
],
),
),
_isLoading = true; ],
),
const SizedBox(height: 16),
InkWell(
}); onTap: () async {
final confirmed = await showDialog<bool>(
context: context,
builder: (context) => AlertDialog(
title: const Text('确认退出'),
content: const Text('您确定要退出登录吗?'),
actions: [
TextButton(
try { onPressed: () => Navigator.pop(context, false),
child: const Text('取消'),
),
TextButton(
String fullResponse = ''; onPressed: () => Navigator.pop(context, true),
child: const Text(
'退出',
style: TextStyle(color: Colors.red),
bool isFirstChunk = true; ),
),
],
),
// 创建一个缓冲区来存储收到的文本 );
if (confirmed == true && context.mounted) {
await StorageService.clearUser();
StringBuffer buffer = StringBuffer();
Navigator.of(context).pushReplacementNamed('/login');
}
},
await for (final chunk in openAIService.chatGPTAPI(userMessage)) { child: Container(
padding: const EdgeInsets.symmetric(
vertical: 12,
horizontal: 16,
buffer.write(chunk); ),
decoration: BoxDecoration(
color: Colors.red[50],
borderRadius: BorderRadius.circular(8),
// 逐字显示文本 ),
child: Row(
mainAxisAlignment: MainAxisAlignment.center,
children: [
for (int i = fullResponse.length; i < buffer.length; i++) { Icon(
Icons.logout,
color: Colors.red[700],
size: 20,
setState(() { ),
const SizedBox(width: 8),
Text(
'退出登录',
fullResponse += buffer.toString()[i]; style: TextStyle(
color: Colors.red[700],
fontSize: 16,
fontWeight: FontWeight.w500,
if (isFirstChunk && i == 0) { ),
),
],
),
messages.add(ChatMessage( ),
),
],
),
text: fullResponse, );
},
),
],
isUserMessage: false, ),
);
}
)); @override
Widget build(BuildContext context) {
return Scaffold(
appBar: widget.hideNavigation ? null : _buildAppBar(),
isFirstChunk = false; drawer: widget.hideNavigation ? null : _buildDrawer(context),
body: IndexedStack(
index: _currentIndex,
children: [
} else { Column(
children: [
Expanded(
child: ListView.builder(
messages.last = ChatMessage( padding: const EdgeInsets.all(16),
itemCount: messages.isEmpty ? 1 : messages.length,
itemBuilder: (context, index) {
if (messages.isEmpty) {
text: fullResponse, return Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
isUserMessage: false, ZoomIn(
child: Stack(
children: [
Center(
); child: Container(
height: 120,
width: 120,
margin: const EdgeInsets.only(top: 4),
} decoration: const BoxDecoration(
color: Pallete.assistantCircleColor,
shape: BoxShape.circle,
),
}); ),
),
Container(
height: 123,
decoration: BoxDecoration(
shape: BoxShape.circle,
image: DecorationImage(
image: widget.customImageUrl != null
// 添加短暂延迟以创建打字效果 ? AssetImage(widget.customImageUrl!)
: const AssetImage(
'assets/images/virtualAssistant.png',
),
await Future.delayed(const Duration(milliseconds: 50)); ),
),
),
],
} ),
),
const SizedBox(height: 20),
Text(
} widget.customDescription ??
'你好!我是你的快际新云AI助手,请问有什么可以帮你的吗?',
style: const TextStyle(
fontSize: 20,
await systemSpeak(fullResponse); color: Pallete.mainFontColor,
),
textAlign: TextAlign.center,
),
await _updateCurrentConversation(); ],
),
);
}
} catch (e) {
final message = messages[index];
return Column(
setState(() { children: [
Align(
alignment: message.isUserMessage
? Alignment.centerRight
messages.add(ChatMessage( : Alignment.centerLeft,
child: Container(
margin: const EdgeInsets.symmetric(vertical: 4),
padding: const EdgeInsets.all(12),
text: '抱歉,出现了一些错误:$e', constraints: BoxConstraints(
maxWidth: MediaQuery.of(context).size.width * 0.7,
),
decoration: BoxDecoration(
isUserMessage: false, color: message.isUserMessage
? Pallete.firstSuggestionBoxColor
: Pallete.assistantCircleColor,
borderRadius: BorderRadius.circular(15).copyWith(
)); bottomRight:
message.isUserMessage ? Radius.zero : null,
bottomLeft:
!message.isUserMessage ? Radius.zero : null,
}); ),
),
child: message.isUserMessage
? Text(
} finally { message.text,
style: const TextStyle(
color: Colors.white,
fontSize: 16,
setState(() { ),
)
: MarkdownBody(
data: message.text,
_isLoading = false; selectable: true,
styleSheet: MarkdownStyleSheet(
p: const TextStyle(
color: Colors.black,
}); fontSize: 16,
),
code: const TextStyle(
color: Colors.white,
} fontFamily: 'monospace',
fontSize: 14,
height: 1.5,
backgroundColor: Colors.transparent,
} ),
codeblockPadding:
const EdgeInsets.all(16),
codeblockDecoration: BoxDecoration(
color: const Color(0xFF1E1E1E),
borderRadius: BorderRadius.circular(8),
),
blockquote: const TextStyle(
Future<void> _processAIResponse(String userInput) async { color: Colors.black87,
fontSize: 16,
height: 1.5,
),
try { blockquoteDecoration: BoxDecoration(
border: Border(
left: BorderSide(
color: Colors.grey[300]!,
String fullResponse = ''; width: 4,
),
),
),
bool isFirstChunk = true; listBullet: const TextStyle(
color: Colors.black87),
),
),
// 创建一个缓冲区来储收到的文本 ),
),
if (_isLoading &&
index == messages.length - 1 &&
StringBuffer buffer = StringBuffer(); message.isUserMessage)
Padding(
padding: const EdgeInsets.all(8.0),
child: Align(
await for (final chunk in openAIService.chatGPTAPI(userInput)) { alignment: Alignment.centerLeft,
child: Row(
mainAxisSize: MainAxisSize.min,
children: [
buffer.write(chunk); SizedBox(
width: 20,
height: 20,
child: CircularProgressIndicator(
strokeWidth: 2,
valueColor: AlwaysStoppedAnimation<Color>(
Pallete.firstSuggestionBoxColor,
),
// 逐字显示文本 ),
),
const SizedBox(width: 8),
const Text(
for (int i = fullResponse.length; i < buffer.length; i++) { '正在思考中...',
style: TextStyle(
color: Pallete.mainFontColor,
fontSize: 14,
setState(() { ),
),
],
),
fullResponse += buffer.toString()[i]; ),
),
],
);
if (isFirstChunk && i == 0) { },
),
),
_buildBottomInput(),
messages.add(ChatMessage( ],
),
if (!widget.hideNavigation) AppsPage(),
],
text: fullResponse, ),
);
}
}
isUserMessage: false,
));
isFirstChunk = false;
} else {
messages.last = ChatMessage(
text: fullResponse,
isUserMessage: false,
);
}
});
// 添加短暂延迟以创建打字效果
await Future.delayed(const Duration(milliseconds: 50));
}
}
await systemSpeak(fullResponse);
await _updateCurrentConversation();
} catch (e) {
setState(() {
messages.add(ChatMessage(
text: '抱歉,出现了一些错误:$e',
isUserMessage: false,
));
});
} finally {
setState(() {
_isLoading = false;
});
}
}
@override
void dispose() {
super.dispose();
speechToText.stop();
flutterTts.stop();
_messageController.dispose();
}
Widget _buildBottomInput() {
return Container(
padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 8),
decoration: BoxDecoration(
color: Colors.white,
boxShadow: [
BoxShadow(
color: Colors.grey.withOpacity(0.1),
spreadRadius: 1,
blurRadius: 3,
offset: const Offset(0, -1),
),
],
),
child: Row(
children: [
Expanded(
child: _isVoiceMode
? GestureDetector(
onLongPressStart: (_) async {
setState(() {
_isListeningPressed = true;
_currentVoiceText = '';
});
await startListening();
},
onLongPressEnd: (_) async {
setState(() => _isListeningPressed = false);
await stopListening();
final finalVoiceText = _currentVoiceText;
if (finalVoiceText.isNotEmpty) {
setState(() {
messages.add(ChatMessage(
text: finalVoiceText,
isUserMessage: true,
));
_isLoading = true;
});
await _processAIResponse(finalVoiceText);
}
setState(() {
_currentVoiceText = '';
});
},
child: Container(
padding: const EdgeInsets.symmetric(
horizontal: 20,
vertical: 10,
),
decoration: BoxDecoration(
color: Colors.grey[100],
borderRadius: BorderRadius.circular(25),
),
child: Text(
_isListeningPressed
? (_currentVoiceText.isEmpty
? '正在聆听...'
: _currentVoiceText)
: '按住说话',
textAlign: TextAlign.center,
style: TextStyle(
color: _isListeningPressed
? Pallete.firstSuggestionBoxColor
: Colors.grey[600],
),
),
),
)
: TextField(
controller: _messageController,
decoration: InputDecoration(
hintText: '输入消息...',
border: OutlineInputBorder(
borderRadius: BorderRadius.circular(25),
borderSide: BorderSide.none,
),
filled: true,
fillColor: Colors.grey[100],
contentPadding: const EdgeInsets.symmetric(
horizontal: 20,
vertical: 10,
),
),
),
),
const SizedBox(width: 8),
IconButton(
icon: Icon(
_isVoiceMode ? Icons.keyboard : Icons.mic,
color: Pallete.firstSuggestionBoxColor,
),
onPressed: () {
setState(() => _isVoiceMode = !_isVoiceMode);
},
),
if (!_isVoiceMode)
IconButton(
icon: const Icon(
Icons.send,
color: Pallete.firstSuggestionBoxColor,
),
onPressed: _sendMessage,
),
],
),
);
}
AppBar _buildAppBar() {
return AppBar(
title: Row(
mainAxisAlignment: MainAxisAlignment.center,
children: [
TextButton(
onPressed: () {
setState(() => _currentIndex = 0);
},
child: Text(
'对话',
style: TextStyle(
fontSize: _currentIndex == 0 ? 20 : 16,
fontWeight: _currentIndex == 0 ? FontWeight.bold : FontWeight.normal,
color: _currentIndex == 0
? Pallete.firstSuggestionBoxColor
: Colors.grey,
),
),
),
const SizedBox(width: 20),
TextButton(
onPressed: () {
setState(() => _currentIndex = 1);
},
child: Text(
'应用',
style: TextStyle(
fontSize: _currentIndex == 1 ? 20 : 16,
fontWeight: _currentIndex == 1 ? FontWeight.bold : FontWeight.normal,
color: _currentIndex == 1
? Pallete.firstSuggestionBoxColor
: Colors.grey,
),
),
),
],
),
leading: Builder(
builder: (context) => IconButton(
icon: const Icon(Icons.menu),
onPressed: () => Scaffold.of(context).openDrawer(),
),
),
);
}
Widget _buildDrawer(BuildContext context) {
return Drawer(
child: Column(
children: [
DrawerHeader(
decoration: BoxDecoration(
color: Pallete.firstSuggestionBoxColor,
),
child: const Center(
child: Text(
'会话列表',
style: TextStyle(
color: Colors.white,
fontSize: 24,
),
),
),
),
ListTile(
leading: const Icon(Icons.add),
title: const Text('新建会话'),
onTap: () {
_createNewConversation();
Navigator.pop(context);
},
),
Expanded(
child: ListView.builder(
itemCount: _conversations.length,
itemBuilder: (context, index) {
final conversation = _conversations[index];
return ListTile(
leading: const Icon(Icons.chat),
title: Text(conversation.title),
subtitle: Text(
conversation.messages.isEmpty
? '暂无消息'
: conversation.messages.last.text,
maxLines: 1,
overflow: TextOverflow.ellipsis,
),
selected: _currentConversation.id == conversation.id,
onTap: () {
setState(() {
_currentConversation = conversation;
messages = conversation.messages;
});
Navigator.pop(context);
},
trailing: IconButton(
icon: const Icon(Icons.delete),
onPressed: () async {
await _storageService.deleteConversation(conversation.id);
setState(() {
_conversations.removeAt(index);
if (_currentConversation.id == conversation.id) {
if (_conversations.isEmpty) {
_createNewConversation();
} else {
_currentConversation = _conversations.first;
messages = _currentConversation.messages;
}
}
});
},
),
);
},
),
),
const Spacer(),
const Divider(height: 1),
FutureBuilder<User?>(
future: StorageService.getUser(),
builder: (context, snapshot) {
if (!snapshot.hasData) return const SizedBox();
return Container(
padding: const EdgeInsets.all(16),
decoration: BoxDecoration(
color: Colors.grey[50],
),
child: Column(
children: [
Row(
children: [
Container(
width: 50,
height: 50,
decoration: BoxDecoration(
color: Pallete.firstSuggestionBoxColor,
shape: BoxShape.circle,
),
child: Center(
child: Text(
snapshot.data!.username[0].toUpperCase(),
style: const TextStyle(
color: Colors.white,
fontSize: 24,
fontWeight: FontWeight.bold,
),
),
),
),
const SizedBox(width: 16),
Expanded(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
snapshot.data!.username,
style: const TextStyle(
fontSize: 18,
fontWeight: FontWeight.bold,
),
),
const SizedBox(height: 4),
Text(
'在线',
style: TextStyle(
fontSize: 14,
color: Colors.green[600],
),
),
],
),
),
],
),
const SizedBox(height: 16),
InkWell(
onTap: () async {
final confirmed = await showDialog<bool>(
context: context,
builder: (context) => AlertDialog(
title: const Text('确认退出'),
content: const Text('您确定要退出登录吗?'),
actions: [
TextButton(
onPressed: () => Navigator.pop(context, false),
child: const Text('取消'),
),
TextButton(
onPressed: () => Navigator.pop(context, true),
child: const Text(
'退出',
style: TextStyle(color: Colors.red),
),
),
],
),
);
if (confirmed == true && context.mounted) {
await StorageService.clearUser();
Navigator.of(context).pushReplacementNamed('/login');
}
},
child: Container(
padding: const EdgeInsets.symmetric(
vertical: 12,
horizontal: 16,
),
decoration: BoxDecoration(
color: Colors.red[50],
borderRadius: BorderRadius.circular(8),
),
child: Row(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Icon(
Icons.logout,
color: Colors.red[700],
size: 20,
),
const SizedBox(width: 8),
Text(
'退出登录',
style: TextStyle(
color: Colors.red[700],
fontSize: 16,
fontWeight: FontWeight.w500,
),
),
],
),
),
),
],
),
);
},
),
],
),
);
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: widget.hideNavigation ? null : _buildAppBar(),
drawer: widget.hideNavigation ? null : _buildDrawer(context),
body: IndexedStack(
index: _currentIndex,
children: [
Column(
children: [
Expanded(
child: ListView.builder(
padding: const EdgeInsets.all(16),
itemCount: messages.isEmpty ? 1 : messages.length,
itemBuilder: (context, index) {
if (messages.isEmpty) {
return Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
ZoomIn(
child: Stack(
children: [
Center(
child: Container(
height: 120,
width: 120,
margin: const EdgeInsets.only(top: 4),
decoration: const BoxDecoration(
color: Pallete.assistantCircleColor,
shape: BoxShape.circle,
),
),
),
Container(
height: 123,
decoration: BoxDecoration(
shape: BoxShape.circle,
image: DecorationImage(
image: widget.customImageUrl != null
? AssetImage(widget.customImageUrl!)
: const AssetImage(
'assets/images/virtualAssistant.png',
),
),
),
),
],
),
),
const SizedBox(height: 20),
Text(
widget.customDescription ??
'你好!我是你的快际新云AI助手,请问有什么可以帮你的吗?',
style: const TextStyle(
fontSize: 20,
color: Pallete.mainFontColor,
),
textAlign: TextAlign.center,
),
],
),
);
}
final message = messages[index];
return Column(
children: [
Align(
alignment: message.isUserMessage
? Alignment.centerRight
: Alignment.centerLeft,
child: Container(
margin: const EdgeInsets.symmetric(vertical: 4),
padding: const EdgeInsets.all(12),
constraints: BoxConstraints(
maxWidth: MediaQuery.of(context).size.width * 0.7,
),
decoration: BoxDecoration(
color: message.isUserMessage
? Pallete.firstSuggestionBoxColor
: Pallete.assistantCircleColor,
borderRadius: BorderRadius.circular(15).copyWith(
bottomRight:
message.isUserMessage ? Radius.zero : null,
bottomLeft:
!message.isUserMessage ? Radius.zero : null,
),
),
child: message.isUserMessage
? Text(
message.text,
style: const TextStyle(
color: Colors.white,
fontSize: 16,
),
)
: MarkdownBody(
data: message.text,
selectable: true,
styleSheet: MarkdownStyleSheet(
p: const TextStyle(
color: Colors.black,
fontSize: 16,
),
code: const TextStyle(
color: Colors.white,
fontFamily: 'monospace',
fontSize: 14,
height: 1.5,
backgroundColor: Colors.transparent,
),
codeblockPadding:
const EdgeInsets.all(16),
codeblockDecoration: BoxDecoration(
color: const Color(0xFF1E1E1E),
borderRadius: BorderRadius.circular(8),
),
blockquote: const TextStyle(
color: Colors.black87,
fontSize: 16,
height: 1.5,
),
blockquoteDecoration: BoxDecoration(
border: Border(
left: BorderSide(
color: Colors.grey[300]!,
width: 4,
),
),
),
listBullet: const TextStyle(
color: Colors.black87),
),
),
),
),
if (_isLoading &&
index == messages.length - 1 &&
message.isUserMessage)
Padding(
padding: const EdgeInsets.all(8.0),
child: Align(
alignment: Alignment.centerLeft,
child: Row(
mainAxisSize: MainAxisSize.min,
children: [
SizedBox(
width: 20,
height: 20,
child: CircularProgressIndicator(
strokeWidth: 2,
valueColor: AlwaysStoppedAnimation<Color>(
Pallete.firstSuggestionBoxColor,
),
),
),
const SizedBox(width: 8),
const Text(
'正在思考中...',
style: TextStyle(
color: Pallete.mainFontColor,
fontSize: 14,
),
),
],
),
),
),
],
);
},
),
),
_buildBottomInput(),
],
),
if (!widget.hideNavigation) AppsPage(),
],
),
);
}
}
\ No newline at end of file
class AppItem { class AppItem {
final String id;
final String name; final String name;
final String description; final String description;
final String imageUrl; final String iconUrl;
final String? appCode;
final String openingStatement;
final List<String> suggestedQuestions;
final bool isDefault;
AppItem({ AppItem({
required this.id,
required this.name, required this.name,
required this.description, required this.description,
required this.imageUrl, required this.iconUrl,
this.appCode,
required this.openingStatement,
required this.suggestedQuestions,
required this.isDefault,
}); });
factory AppItem.fromJson(Map<String, dynamic> json) {
return AppItem(
name: json['name'] ?? '',
description: json['description'] ?? '',
iconUrl: json['icon_url'] ?? '',
appCode: json['app_code'],
openingStatement: json['opening_statement'] ?? '',
suggestedQuestions: List<String>.from(json['suggested_questions'] ?? []),
isDefault: json['is_default'] ?? false,
);
}
} }
import 'package:flutter/material.dart'; import 'package:flutter/material.dart';
import '../services/apps_service.dart';
import '../models/app_item.dart'; import '../models/app_item.dart';
import '../pallete.dart'; import '../pallete.dart';
import '../services/storage_service.dart';
import '../models/user.dart';
class AppsPage extends StatelessWidget { class AppsPage extends StatefulWidget {
AppsPage({super.key}); const AppsPage({super.key});
final List<AppItem> apps = [ @override
AppItem( State<AppsPage> createState() => _AppsPageState();
id: '1', }
name: '文章助手',
description: '帮助您撰写高质量的文章,提供创意和灵感', class _AppsPageState extends State<AppsPage> {
imageUrl: 'assets/images/article.png', late final AppsService _appsService;
), List<AppItem> apps = [];
AppItem( bool isLoading = true;
id: '2', String? error;
name: '代码专家',
description: '解答编程问题,优化代码结构,提供最佳实践', @override
imageUrl: 'assets/images/code.png', void initState() {
), super.initState();
AppItem( _initializeService();
id: '3', }
name: '翻译助手',
description: '精准翻译多国语言,支持专业术语翻译', Future<void> _initializeService() async {
imageUrl: 'assets/images/translate.png', final User? user = await StorageService.getUser();
), _appsService = AppsService(token: user?.token);
AppItem( fetchApps();
id: '4', }
name: '数学导师',
description: '解决数学问题,讲解数学概念和公式', Future<void> fetchApps() async {
imageUrl: 'assets/images/math.png', try {
), final appsList = await _appsService.getApps();
AppItem( setState(() {
id: '5', apps = appsList;
name: '生活顾问', isLoading = false;
description: '提供日常生活建议,解答各类生活问题', });
imageUrl: 'assets/images/life.png', } catch (e) {
), setState(() {
]; error = e.toString();
isLoading = false;
});
}
}
@override @override
Widget build(BuildContext context) { Widget build(BuildContext context) {
if (isLoading) {
return const Center(child: CircularProgressIndicator());
}
if (error != null) {
return Center(child: Text(error!));
}
return ListView.builder( return ListView.builder(
padding: const EdgeInsets.all(16), padding: const EdgeInsets.all(16),
itemCount: apps.length, itemCount: apps.length,
...@@ -57,10 +72,19 @@ class AppsPage extends StatelessWidget { ...@@ -57,10 +72,19 @@ class AppsPage extends StatelessWidget {
color: Pallete.firstSuggestionBoxColor.withOpacity(0.1), color: Pallete.firstSuggestionBoxColor.withOpacity(0.1),
borderRadius: BorderRadius.circular(12), borderRadius: BorderRadius.circular(12),
), ),
child: Icon( child: ClipRRect(
Icons.apps, borderRadius: BorderRadius.circular(12),
size: 30, child: Image.network(
color: Pallete.firstSuggestionBoxColor, app.iconUrl,
fit: BoxFit.cover,
errorBuilder: (context, error, stackTrace) {
return Icon(
Icons.apps,
size: 30,
color: Pallete.firstSuggestionBoxColor,
);
},
),
), ),
), ),
title: Text( title: Text(
......
import 'package:flutter/material.dart'; import 'package:flutter/material.dart';
import '../models/app_item.dart'; import '../models/app_item.dart';
import '../home_page.dart'; import '../home_page.dart';
class ChatPage extends StatelessWidget { class ChatPage extends StatelessWidget {
final AppItem app; final AppItem app;
const ChatPage({super.key, required this.app}); const ChatPage({super.key, required this.app});
@override @override
Widget build(BuildContext context) { Widget build(BuildContext context) {
return Scaffold( return Scaffold(
appBar: AppBar( appBar: AppBar(
title: Column( title: Column(
crossAxisAlignment: CrossAxisAlignment.start, crossAxisAlignment: CrossAxisAlignment.start,
children: [ children: [
Text( Text(
app.name, app.name,
style: const TextStyle( style: const TextStyle(
fontSize: 18, fontSize: 18,
fontWeight: FontWeight.bold, fontWeight: FontWeight.bold,
), ),
), ),
Text( Text(
app.description, app.description,
style: const TextStyle( style: const TextStyle(
fontSize: 12, fontSize: 12,
fontWeight: FontWeight.normal, fontWeight: FontWeight.normal,
), ),
), ),
], ],
), ),
leading: IconButton( leading: IconButton(
icon: const Icon(Icons.arrow_back), icon: const Icon(Icons.arrow_back),
onPressed: () => Navigator.of(context).pop(), onPressed: () => Navigator.of(context).pop(),
), ),
), ),
body: HomePage( body: HomePage(
customTitle: app.name, customTitle: app.name,
customDescription: app.description, customDescription: app.description,
customImageUrl: app.imageUrl, customImageUrl: app.iconUrl,
hideNavigation: true, hideNavigation: true,
), ),
); );
} }
} }
\ No newline at end of file
const openAIAPIKey = 'sk-zV0MPjPserDD4gdQ8lE8aUGwxayOwuayogGidos4VO8uxdDL'; const openAIAPIKey = 'sk-zV0MPjPserDD4gdQ8lE8aUGwxayOwuayogGidos4VO8uxdDL';
const baseUrl = 'https://knowledge-web.apps.iytcloud.com/console/api';
import 'dart:convert'; import 'dart:convert';
import 'package:http/http.dart' as http; import 'package:http/http.dart' as http;
import '../secrets.dart';
class ApiService { class ApiService {
static const String baseUrl =
'https://knowledge-web.apps.iytcloud.com/console/api';
static Future<Map<String, dynamic>> login( static Future<Map<String, dynamic>> login(
String email, String password) async { String email, String password) async {
final response = await http.post( final response = await http.post(
......
import 'dart:convert';
import 'package:http/http.dart' as http;
import '../models/app_item.dart';
import '../secrets.dart';
class AppsService {
final String? token;
AppsService({this.token});
Future<List<AppItem>> getApps({int page = 1, int limit = 12}) async {
final response = await http.get(
Uri.parse('$baseUrl/apps/?page=$page&limit=$limit'),
headers: {
'Content-Type': 'application/json',
'Accept': 'application/json',
if (token != null) 'Authorization': 'Bearer $token',
},
);
if (response.statusCode == 200) {
final Map<String, dynamic> responseData = json.decode(response.body);
final List<dynamic> appsData = responseData['data'];
return appsData.map((json) => AppItem.fromJson(json)).toList();
} else {
throw Exception('获取应用列表失败: ${response.statusCode}');
}
}
}
import 'dart:convert'; import 'dart:convert';
import 'package:http/http.dart' as http; import 'package:http/http.dart' as http;
import '../secrets.dart';
class OpenAIService { class OpenAIService {
final String baseUrl =
'https://knowledge-web.apps.iytcloud.com/console/api/openapi/chat';
final String apiKey = 'sk-OVjS7VE9mT68Uvg7kSFoMnbU6EU836FO'; final String apiKey = 'sk-OVjS7VE9mT68Uvg7kSFoMnbU6EU836FO';
final String appKey = 'app-FRP2s2wSx01rsE67'; final String appKey = 'app-FRP2s2wSx01rsE67';
String? conversationId; String? conversationId;
...@@ -13,7 +12,7 @@ class OpenAIService { ...@@ -13,7 +12,7 @@ class OpenAIService {
var buffer = StringBuffer(); var buffer = StringBuffer();
try { try {
final request = http.Request('POST', Uri.parse(baseUrl)); final request = http.Request('POST', Uri.parse('$baseUrl/openapi/chat'));
request.headers.addAll({ request.headers.addAll({
'Content-Type': 'application/json', 'Content-Type': 'application/json',
'Authorization': 'Bearer $apiKey', 'Authorization': 'Bearer $apiKey',
......
...@@ -70,11 +70,6 @@ flutter: ...@@ -70,11 +70,6 @@ flutter:
assets: assets:
- assets/images/ - assets/images/
- assets/sounds/ - assets/sounds/
- assets/images/article.png
- assets/images/code.png
- assets/images/translate.png
- assets/images/math.png
- assets/images/life.png
# An image asset can refer to one or more resolution-specific "variants", see # An image asset can refer to one or more resolution-specific "variants", see
# https://flutter.dev/assets-and-images/#resolution-aware # https://flutter.dev/assets-and-images/#resolution-aware
......
Markdown 格式
0%
您添加了 0 到此讨论。请谨慎行事。
请先完成此评论的编辑!
注册 或者 后发表评论