提交 e92fe5f9 authored 作者: songchuancai's avatar songchuancai

调整应用和对话页面布局

上级 056bceaf
import 'package:allen/pallete.dart'; import 'package:allen/pallete.dart';
import 'package:animate_do/animate_do.dart';
import 'package:flutter/material.dart';
import 'package:flutter_tts/flutter_tts.dart';
import 'package:speech_to_text/speech_recognition_result.dart'; import 'package:animate_do/animate_do.dart';
import 'package:speech_to_text/speech_to_text.dart';
import 'package:flutter/foundation.dart' show kIsWeb;
import 'package:uuid/uuid.dart';
import 'models/conversation.dart'; import 'package:flutter/material.dart';
import 'services/storage_service.dart';
import 'services/chat_service.dart';
import 'models/chat_message.dart';
import 'models/user.dart'; import 'package:flutter_tts/flutter_tts.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:flutter_markdown/flutter_markdown.dart';
class HomePage extends StatefulWidget { import 'package:speech_to_text/speech_recognition_result.dart';
const HomePage({super.key});
@override
State<HomePage> createState() => _HomePageState(); import 'package:speech_to_text/speech_to_text.dart';
}
class _HomePageState extends State<HomePage> {
final speechToText = SpeechToText(); import 'package:flutter/foundation.dart' show kIsWeb;
final flutterTts = FlutterTts();
String lastWords = '';
final OpenAIService openAIService = OpenAIService();
String? generatedContent; import 'package:uuid/uuid.dart';
String? generatedImageUrl;
int start = 200;
int delay = 200;
final TextEditingController _messageController = TextEditingController(); import 'models/conversation.dart';
String currentStreamedContent = '';
List<ChatMessage> messages = [];
bool _isLoading = false;
bool _isVoiceMode = true; import 'services/storage_service.dart';
bool _isListeningPressed = false;
String _currentVoiceText = '';
late StorageService _storageService;
late SharedPreferences _prefs; import 'services/chat_service.dart';
late Conversation _currentConversation;
List<Conversation> _conversations = [];
@override import 'models/chat_message.dart';
void initState() {
super.initState();
_initializeStorage();
initSpeechToText(); import 'models/user.dart';
_initTts();
}
Future<void> _initializeStorage() async { import 'package:shared_preferences/shared_preferences.dart';
_prefs = await SharedPreferences.getInstance();
_storageService = StorageService(_prefs);
_conversations = await _storageService.getConversations();
if (_conversations.isEmpty) { import 'package:flutter_markdown/flutter_markdown.dart';
_createNewConversation();
} else {
_currentConversation = _conversations.first;
setState(() { import 'pages/apps_page.dart';
messages = _currentConversation.messages;
});
}
}
Future<void> _createNewConversation() async {
final newConversation = Conversation(
id: const Uuid().v4(), class HomePage extends StatefulWidget {
title: '新会话 ${_conversations.length + 1}',
createdAt: DateTime.now(),
messages: [],
); final String? customTitle;
await _storageService.addConversation(newConversation);
setState(() {
_conversations.insert(0, newConversation); final String? customDescription;
_currentConversation = newConversation;
messages = [];
});
} final String? customImageUrl;
Future<void> _updateCurrentConversation() async {
_currentConversation = Conversation(
id: _currentConversation.id, final bool hideNavigation;
title: _currentConversation.title,
createdAt: _currentConversation.createdAt,
messages: messages,
);
await _storageService.updateConversation(_currentConversation);
}
Future<void> _initTts() async { const HomePage({
if (!kIsWeb) {
await flutterTts.setSharedInstance(true);
}
setState(() {}); super.key,
}
Future<void> initSpeechToText() async {
await speechToText.initialize(); this.customTitle,
setState(() {});
}
Future<void> startListening() async { this.customDescription,
await speechToText.listen(onResult: onSpeechResult);
setState(() {});
}
this.customImageUrl,
Future<void> stopListening() async {
await speechToText.stop();
setState(() {});
} this.hideNavigation = false,
Future<void> onSpeechResult(SpeechRecognitionResult result) async {
setState(() {
lastWords = result.recognizedWords; });
_currentVoiceText = result.recognizedWords;
});
}
Future<void> systemSpeak(String content) async {
try {
if (kIsWeb) {
// 设置语速 @override
await flutterTts.setSpeechRate(3);
// 音调
await flutterTts.setPitch(0.8);
await flutterTts.speak(content); State<HomePage> createState() => _HomePageState();
} else {
await flutterTts.setSharedInstance(true);
await flutterTts.speak(content);
} }
} catch (e) {
print('TTS Error: $e');
}
}
Future<void> _sendMessage() async {
if (_messageController.text.isEmpty) return;
class _HomePageState extends State<HomePage> {
String userMessage = _messageController.text;
_messageController.clear();
setState(() { final speechToText = SpeechToText();
messages.add(ChatMessage(
text: userMessage,
isUserMessage: true,
)); final flutterTts = FlutterTts();
currentStreamedContent = '';
_isLoading = true;
});
String lastWords = '';
try {
String fullResponse = '';
bool isFirstChunk = true;
// 创建一个缓冲区来存储收到的文本 final OpenAIService openAIService = OpenAIService();
StringBuffer buffer = StringBuffer();
await for (final chunk in openAIService.chatGPTAPI(userMessage)) {
buffer.write(chunk);
// 逐字显示文本 String? generatedContent;
for (int i = fullResponse.length; i < buffer.length; i++) {
setState(() {
fullResponse += buffer.toString()[i];
if (isFirstChunk && i == 0) { String? generatedImageUrl;
messages.add(ChatMessage(
text: fullResponse,
isUserMessage: false,
)); int start = 200;
isFirstChunk = false;
} else {
messages.last = ChatMessage(
text: fullResponse, int delay = 200;
isUserMessage: false,
);
}
}); final TextEditingController _messageController = TextEditingController();
// 添加短暂延迟以创建打字效果
await Future.delayed(const Duration(milliseconds: 50));
} String currentStreamedContent = '';
}
await systemSpeak(fullResponse);
await _updateCurrentConversation();
} catch (e) { List<ChatMessage> messages = [];
setState(() {
messages.add(ChatMessage(
text: '抱歉,出现了一些错误:$e',
isUserMessage: false, bool _isLoading = false;
));
});
} finally {
setState(() { bool _isVoiceMode = true;
_isLoading = false;
});
}
} bool _isListeningPressed = false;
Future<void> _processAIResponse(String userInput) async {
try {
String fullResponse = ''; String _currentVoiceText = '';
bool isFirstChunk = true;
// 创建一个缓冲区来存储收到的文本
StringBuffer buffer = StringBuffer();
await for (final chunk in openAIService.chatGPTAPI(userInput)) { late StorageService _storageService;
buffer.write(chunk);
// 逐字显示文本
for (int i = fullResponse.length; i < buffer.length; i++) { late SharedPreferences _prefs;
setState(() {
fullResponse += buffer.toString()[i];
if (isFirstChunk && i == 0) {
messages.add(ChatMessage( late Conversation _currentConversation;
text: fullResponse,
isUserMessage: false,
));
isFirstChunk = false; List<Conversation> _conversations = [];
} else {
messages.last = ChatMessage(
text: fullResponse,
isUserMessage: false, int _currentIndex = 0;
);
}
});
// 添加短暂延迟以创建打字效果
await Future.delayed(const Duration(milliseconds: 50));
}
} @override
await systemSpeak(fullResponse);
await _updateCurrentConversation();
} catch (e) {
setState(() { void initState() {
messages.add(ChatMessage(
text: '抱歉,出现了一些错误:$e',
isUserMessage: false,
)); super.initState();
});
} finally {
setState(() {
_isLoading = false; _initializeStorage();
});
}
}
initSpeechToText();
@override
void dispose() {
super.dispose();
speechToText.stop(); _initTts();
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), Future<void> _initializeStorage() async {
spreadRadius: 1,
blurRadius: 3,
offset: const Offset(0, -1),
), _prefs = await SharedPreferences.getInstance();
],
),
child: Row(
children: [ _storageService = StorageService(_prefs);
Expanded(
child: _isVoiceMode
? GestureDetector(
onLongPressStart: (_) async { _conversations = await _storageService.getConversations();
setState(() {
_isListeningPressed = true;
_currentVoiceText = '';
}); if (_conversations.isEmpty) {
await startListening();
},
onLongPressEnd: (_) async {
setState(() => _isListeningPressed = false); _createNewConversation();
await stopListening();
final finalVoiceText = _currentVoiceText;
if (finalVoiceText.isNotEmpty) { } else {
setState(() {
messages.add(ChatMessage(
text: finalVoiceText,
isUserMessage: true, _currentConversation = _conversations.first;
));
_isLoading = true;
});
await _processAIResponse(finalVoiceText); setState(() {
}
setState(() {
_currentVoiceText = ''; messages = _currentConversation.messages;
});
},
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 Future<void> _createNewConversation() async {
? Pallete.firstSuggestionBoxColor
: Colors.grey[600],
),
), final newConversation = Conversation(
),
)
: TextField(
controller: _messageController, id: const Uuid().v4(),
decoration: InputDecoration(
hintText: '输入消息...',
border: OutlineInputBorder(
borderRadius: BorderRadius.circular(25), title: '新会话 ${_conversations.length + 1}',
borderSide: BorderSide.none,
),
filled: true,
fillColor: Colors.grey[100], createdAt: DateTime.now(),
contentPadding: const EdgeInsets.symmetric(
horizontal: 20,
vertical: 10,
), messages: [],
),
),
),
const SizedBox(width: 8), );
IconButton(
icon: Icon(
_isVoiceMode ? Icons.keyboard : Icons.mic,
color: Pallete.firstSuggestionBoxColor,
),
onPressed: () {
setState(() => _isVoiceMode = !_isVoiceMode);
}, await _storageService.addConversation(newConversation);
),
if (!_isVoiceMode)
IconButton(
icon: const Icon( setState(() {
Icons.send,
color: Pallete.firstSuggestionBoxColor,
),
onPressed: _sendMessage, _conversations.insert(0, newConversation);
),
],
),
); _currentConversation = newConversation;
}
AppBar _buildAppBar() {
return AppBar( messages = [];
title: BounceInDown(
child: const Text('快际新云'),
),
leading: Builder( });
builder: (context) => IconButton(
icon: const Icon(Icons.menu),
onPressed: () => Scaffold.of(context).openDrawer(),
), }
),
centerTitle: true,
);
}
Widget _buildDrawer(BuildContext context) {
return Drawer(
child: Column( Future<void> _updateCurrentConversation() async {
children: [
DrawerHeader(
decoration: BoxDecoration(
color: Pallete.firstSuggestionBoxColor, _currentConversation = Conversation(
),
child: const Center(
child: Text(
'会话列表', id: _currentConversation.id,
style: TextStyle(
color: Colors.white,
fontSize: 24,
), title: _currentConversation.title,
),
),
),
ListTile( createdAt: _currentConversation.createdAt,
leading: const Icon(Icons.add),
title: const Text('新建会话'),
onTap: () {
_createNewConversation(); messages: messages,
Navigator.pop(context);
},
),
Expanded( );
child: ListView.builder(
itemCount: _conversations.length,
itemBuilder: (context, index) {
final conversation = _conversations[index]; await _storageService.updateConversation(_currentConversation);
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: () { Future<void> _initTts() async {
setState(() {
_currentConversation = conversation;
messages = conversation.messages;
}); if (!kIsWeb) {
Navigator.pop(context);
},
trailing: IconButton(
icon: const Icon(Icons.delete), await flutterTts.setSharedInstance(true);
onPressed: () async {
await _storageService.deleteConversation(conversation.id);
setState(() {
_conversations.removeAt(index); }
if (_currentConversation.id == conversation.id) {
if (_conversations.isEmpty) {
_createNewConversation();
} else { setState(() {});
_currentConversation = _conversations.first;
messages = _currentConversation.messages;
}
} }
});
},
),
);
},
),
),
const Spacer(), Future<void> initSpeechToText() async {
const Divider(height: 1),
FutureBuilder<User?>(
future: StorageService.getUser(),
builder: (context, snapshot) { await speechToText.initialize();
if (!snapshot.hasData) return const SizedBox();
return Container(
padding: const EdgeInsets.all(16),
decoration: BoxDecoration( setState(() {});
color: Colors.grey[50],
),
child: Column(
children: [ }
Row(
children: [
Container(
width: 50,
height: 50,
decoration: BoxDecoration(
color: Pallete.firstSuggestionBoxColor,
shape: BoxShape.circle, Future<void> startListening() async {
),
child: Center(
child: Text(
snapshot.data!.username[0].toUpperCase(), await speechToText.listen(onResult: onSpeechResult);
style: const TextStyle(
color: Colors.white,
fontSize: 24,
fontWeight: FontWeight.bold, setState(() {});
),
),
),
), }
const SizedBox(width: 16),
Expanded(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
snapshot.data!.username,
style: const TextStyle( Future<void> stopListening() async {
fontSize: 18,
fontWeight: FontWeight.bold,
),
), await speechToText.stop();
const SizedBox(height: 4),
Text(
'在线',
style: TextStyle( setState(() {});
fontSize: 14,
color: Colors.green[600],
),
), }
],
),
),
],
),
const SizedBox(height: 16),
InkWell(
onTap: () async { Future<void> onSpeechResult(SpeechRecognitionResult result) async {
final confirmed = await showDialog<bool>(
context: context,
builder: (context) => AlertDialog(
title: const Text('确认退出'), setState(() {
content: const Text('您确定要退出登录吗?'),
actions: [
TextButton(
onPressed: () => Navigator.pop(context, false), lastWords = result.recognizedWords;
child: const Text('取消'),
),
TextButton(
onPressed: () => Navigator.pop(context, true), _currentVoiceText = result.recognizedWords;
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( Future<void> systemSpeak(String content) async {
vertical: 12,
horizontal: 16,
),
decoration: BoxDecoration( try {
color: Colors.red[50],
borderRadius: BorderRadius.circular(8),
),
child: Row( if (kIsWeb) {
mainAxisAlignment: MainAxisAlignment.center,
children: [
Icon(
Icons.logout, // 设置语速
color: Colors.red[700],
size: 20,
),
const SizedBox(width: 8), await flutterTts.setSpeechRate(3);
Text(
'退出登录',
style: TextStyle(
color: Colors.red[700], // 音调
fontSize: 16,
fontWeight: FontWeight.w500,
),
), await flutterTts.setPitch(0.8);
],
),
),
), await flutterTts.speak(content);
],
),
);
}, } else {
),
],
),
); await flutterTts.setSharedInstance(true);
}
@override
Widget build(BuildContext context) { await flutterTts.speak(content);
return Scaffold(
appBar: _buildAppBar(),
drawer: _buildDrawer(context),
body: Column( }
children: [
Expanded(
child: ListView.builder(
padding: const EdgeInsets.all(16), } catch (e) {
itemCount: messages.isEmpty ? 1 : messages.length,
itemBuilder: (context, index) {
if (messages.isEmpty) {
return Center( print('TTS Error: $e');
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,
),
), Future<void> _sendMessage() async {
),
Container(
height: 123,
decoration: const BoxDecoration( if (_messageController.text.isEmpty) return;
shape: BoxShape.circle,
image: DecorationImage(
image: AssetImage(
'assets/images/virtualAssistant.png',
),
),
),
), String userMessage = _messageController.text;
],
),
),
const SizedBox(height: 20), _messageController.clear();
const Text(
'你好!我是你的快际新云AI助手,请问有什么可以帮你的吗?',
style: TextStyle(
fontSize: 20,
color: Pallete.mainFontColor,
),
),
], setState(() {
),
);
}
messages.add(ChatMessage(
final message = messages[index];
return Column(
children: [
Align( text: userMessage,
alignment: message.isUserMessage
? Alignment.centerRight
: Alignment.centerLeft,
child: Container( isUserMessage: true,
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 currentStreamedContent = '';
: Pallete.assistantCircleColor,
borderRadius: BorderRadius.circular(15).copyWith(
bottomRight:
message.isUserMessage ? Radius.zero : null, _isLoading = true;
bottomLeft:
!message.isUserMessage ? Radius.zero : null,
),
), });
child: message.isUserMessage
? Text(
message.text,
style: const TextStyle(
color: Colors.white,
fontSize: 16,
),
) try {
: MarkdownBody(
data: message.text,
selectable: true,
styleSheet: MarkdownStyleSheet( String fullResponse = '';
p: const TextStyle(
color: Colors.black,
fontSize: 16,
), bool isFirstChunk = true;
code: const TextStyle(
color: Colors.white,
fontFamily: 'monospace',
fontSize: 14, // 创建一个缓冲区来存储收到的文本
height: 1.5,
backgroundColor: Colors.transparent,
),
codeblockPadding: const EdgeInsets.all(16), StringBuffer buffer = StringBuffer();
codeblockDecoration: BoxDecoration(
color: const Color(0xFF1E1E1E),
borderRadius: BorderRadius.circular(8),
), await for (final chunk in openAIService.chatGPTAPI(userMessage)) {
blockquote: const TextStyle(
color: Colors.black87,
fontSize: 16,
height: 1.5, buffer.write(chunk);
),
blockquoteDecoration: BoxDecoration(
border: Border(
left: BorderSide( // 逐字显示文本
color: Colors.grey[300]!,
width: 4,
),
), for (int i = fullResponse.length; i < buffer.length; i++) {
),
listBullet:
const TextStyle(color: Colors.black87),
), setState(() {
),
),
),
if (_isLoading && fullResponse += buffer.toString()[i];
index == messages.length - 1 &&
message.isUserMessage)
Padding(
padding: const EdgeInsets.all(8.0), if (isFirstChunk && i == 0) {
child: Align(
alignment: Alignment.centerLeft,
child: Row(
mainAxisSize: MainAxisSize.min, messages.add(ChatMessage(
children: [
SizedBox(
width: 20,
height: 20, text: fullResponse,
child: CircularProgressIndicator(
strokeWidth: 2,
valueColor: AlwaysStoppedAnimation<Color>(
Pallete.firstSuggestionBoxColor, isUserMessage: false,
),
),
),
const SizedBox(width: 8), ));
const Text(
'正在思考中...',
style: TextStyle(
color: Pallete.mainFontColor, isFirstChunk = false;
fontSize: 14,
),
),
], } else {
),
),
),
], messages.last = ChatMessage(
);
},
),
), text: fullResponse,
_buildBottomInput(),
],
),
); 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;
});
}
}
Future<void> _processAIResponse(String userInput) async {
try {
String fullResponse = '';
bool isFirstChunk = true;
// 创建一个缓冲区来储收到的文本
StringBuffer buffer = StringBuffer();
await for (final chunk in openAIService.chatGPTAPI(userInput)) {
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,
);
}
});
// 添加短暂延迟以创建打字效果
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
......
import 'package:allen/home_page.dart'; import 'package:allen/home_page.dart';
import 'package:allen/pallete.dart'; import 'package:allen/pallete.dart';
import 'package:flutter/material.dart'; import 'package:flutter/material.dart';
import 'package:allen/pages/login_page.dart'; import 'package:allen/pages/login_page.dart';
import 'package:allen/services/storage_service.dart'; import 'package:allen/services/storage_service.dart';
import 'package:allen/models/user.dart'; import 'package:allen/models/user.dart';
import 'package:allen/models/app_item.dart';
void main() async { import 'package:allen/pages/chat_page.dart';
WidgetsFlutterBinding.ensureInitialized();
void main() async {
runApp(const MyApp()); WidgetsFlutterBinding.ensureInitialized();
}
runApp(const MyApp());
class MyApp extends StatelessWidget { }
const MyApp({super.key});
class MyApp extends StatelessWidget {
@override const MyApp({super.key});
Widget build(BuildContext context) {
return MaterialApp( @override
debugShowCheckedModeBanner: false, Widget build(BuildContext context) {
title: 'School Assistent', return MaterialApp(
theme: ThemeData.light(useMaterial3: true).copyWith( debugShowCheckedModeBanner: false,
scaffoldBackgroundColor: Pallete.whiteColor, title: 'School Assistent',
appBarTheme: const AppBarTheme( theme: ThemeData.light(useMaterial3: true).copyWith(
backgroundColor: Pallete.whiteColor, scaffoldBackgroundColor: Pallete.whiteColor,
), appBarTheme: const AppBarTheme(
), backgroundColor: Pallete.whiteColor,
home: FutureBuilder<User?>( ),
future: StorageService.getUser(), ),
builder: (context, snapshot) { home: FutureBuilder<User?>(
if (snapshot.connectionState == ConnectionState.waiting) { future: StorageService.getUser(),
return const CircularProgressIndicator(); builder: (context, snapshot) {
} if (snapshot.connectionState == ConnectionState.waiting) {
return snapshot.hasData ? const HomePage() : const LoginPage(); return const CircularProgressIndicator();
}, }
), return snapshot.hasData ? const HomePage() : const LoginPage();
routes: { },
'/home': (context) => const HomePage(), ),
'/login': (context) => const LoginPage(), onGenerateRoute: (settings) {
}, if (settings.name == '/home') {
); return MaterialPageRoute(builder: (context) => const HomePage());
} }
} if (settings.name == '/login') {
return MaterialPageRoute(builder: (context) => const LoginPage());
}
if (settings.name == '/chat') {
final args = settings.arguments;
if (args is AppItem) {
return MaterialPageRoute(
builder: (context) => ChatPage(app: args),
);
}
return MaterialPageRoute(builder: (context) => const HomePage());
}
return MaterialPageRoute(builder: (context) => const HomePage());
},
);
}
}
\ No newline at end of file
......
class AppItem {
final String id;
final String name;
final String description;
final String imageUrl;
AppItem({
required this.id,
required this.name,
required this.description,
required this.imageUrl,
});
}
import 'package:flutter/material.dart';
import '../models/app_item.dart';
import '../pallete.dart';
class AppsPage extends StatelessWidget {
AppsPage({super.key});
final List<AppItem> apps = [
AppItem(
id: '1',
name: '文章助手',
description: '帮助您撰写高质量的文章,提供创意和灵感',
imageUrl: 'assets/images/article.png',
),
AppItem(
id: '2',
name: '代码专家',
description: '解答编程问题,优化代码结构,提供最佳实践',
imageUrl: 'assets/images/code.png',
),
AppItem(
id: '3',
name: '翻译助手',
description: '精准翻译多国语言,支持专业术语翻译',
imageUrl: 'assets/images/translate.png',
),
AppItem(
id: '4',
name: '数学导师',
description: '解决数学问题,讲解数学概念和公式',
imageUrl: 'assets/images/math.png',
),
AppItem(
id: '5',
name: '生活顾问',
description: '提供日常生活建议,解答各类生活问题',
imageUrl: 'assets/images/life.png',
),
];
@override
Widget build(BuildContext context) {
return ListView.builder(
padding: const EdgeInsets.all(16),
itemCount: apps.length,
itemBuilder: (context, index) {
final app = apps[index];
return Card(
margin: const EdgeInsets.only(bottom: 16),
elevation: 2,
child: ListTile(
contentPadding: const EdgeInsets.all(16),
leading: Container(
width: 60,
height: 60,
decoration: BoxDecoration(
color: Pallete.firstSuggestionBoxColor.withOpacity(0.1),
borderRadius: BorderRadius.circular(12),
),
child: Icon(
Icons.apps,
size: 30,
color: Pallete.firstSuggestionBoxColor,
),
),
title: Text(
app.name,
style: const TextStyle(
fontSize: 18,
fontWeight: FontWeight.bold,
),
),
subtitle: Padding(
padding: const EdgeInsets.only(top: 8),
child: Text(
app.description,
style: const TextStyle(fontSize: 14),
),
),
onTap: () {
Navigator.pushNamed(
context,
'/chat',
arguments: app,
);
},
),
);
},
);
}
}
import 'package:flutter/material.dart';
import '../models/app_item.dart';
import '../home_page.dart';
class ChatPage extends StatelessWidget {
final AppItem app;
const ChatPage({super.key, required this.app});
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
app.name,
style: const TextStyle(
fontSize: 18,
fontWeight: FontWeight.bold,
),
),
Text(
app.description,
style: const TextStyle(
fontSize: 12,
fontWeight: FontWeight.normal,
),
),
],
),
leading: IconButton(
icon: const Icon(Icons.arrow_back),
onPressed: () => Navigator.of(context).pop(),
),
),
body: HomePage(
customTitle: app.name,
customDescription: app.description,
customImageUrl: app.imageUrl,
hideNavigation: true,
),
);
}
}
\ No newline at end of file
...@@ -70,6 +70,11 @@ flutter: ...@@ -70,6 +70,11 @@ 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 到此讨论。请谨慎行事。
请先完成此评论的编辑!
注册 或者 后发表评论