117 lines
2.9 KiB
Dart
117 lines
2.9 KiB
Dart
import 'dart:async';
|
|
import 'dart:math';
|
|
import 'package:flutter/material.dart';
|
|
import '../models/message.dart';
|
|
|
|
class ChatProvider extends ChangeNotifier {
|
|
final List<Message> _messages = [];
|
|
bool _isTyping = false;
|
|
String _currentAiResponse = '';
|
|
|
|
List<Message> get messages => List.unmodifiable(_messages);
|
|
bool get isTyping => _isTyping;
|
|
String get currentAiResponse => _currentAiResponse;
|
|
|
|
// Simulated AI responses for demo
|
|
final List<String> _aiResponses = [
|
|
'''# 你好!👋
|
|
|
|
我是你的 AI 助手,很高兴为你服务!
|
|
|
|
我可以帮助你:
|
|
- 回答各种问题
|
|
- 进行创意写作
|
|
- 代码编程辅助
|
|
- 翻译和语言学习
|
|
|
|
有什么我可以帮助你的吗?''',
|
|
'''## 这是一个很好的问题!
|
|
|
|
让我来详细解释一下:
|
|
|
|
1. **首先**,我们需要理解问题的核心
|
|
2. **其次**,分析可能的解决方案
|
|
3. **最后**,选择最优的实现方式
|
|
|
|
```dart
|
|
void main() {
|
|
print('Hello, Flutter!');
|
|
}
|
|
```
|
|
|
|
希望这个解释对你有帮助!''',
|
|
'''### 关于这个话题
|
|
|
|
我有以下几点想法:
|
|
|
|
> "创新是区分领导者和追随者的关键。" — 史蒂夫·乔布斯
|
|
|
|
| 方面 | 优点 | 缺点 |
|
|
|------|------|------|
|
|
| 性能 | ⚡ 快速 | 💾 内存占用 |
|
|
| 易用性 | ✅ 简单 | 📚 学习曲线 |
|
|
|
|
如果你有更多问题,随时问我!''',
|
|
'''我理解你的需求。让我为你提供一些建议:
|
|
|
|
1. 保持代码简洁清晰
|
|
2. 注重用户体验设计
|
|
3. 定期进行代码审查
|
|
4. 编写详细的文档
|
|
|
|
*记住:好的软件不仅仅是功能强大,更要易于使用和维护。*''',
|
|
];
|
|
|
|
void sendMessage(String content) {
|
|
if (content.trim().isEmpty) return;
|
|
|
|
// Add user message
|
|
final userMessage = Message(
|
|
id: DateTime.now().millisecondsSinceEpoch.toString(),
|
|
content: content,
|
|
isUser: true,
|
|
);
|
|
_messages.add(userMessage);
|
|
notifyListeners();
|
|
|
|
// Simulate AI response
|
|
_simulateAiResponse();
|
|
}
|
|
|
|
Future<void> _simulateAiResponse() async {
|
|
_isTyping = true;
|
|
_currentAiResponse = '';
|
|
notifyListeners();
|
|
|
|
// Wait a bit before starting to "type"
|
|
await Future.delayed(const Duration(milliseconds: 800));
|
|
|
|
// Get a random response
|
|
final random = Random();
|
|
final response = _aiResponses[random.nextInt(_aiResponses.length)];
|
|
|
|
// Simulate typing effect
|
|
for (int i = 0; i < response.length; i++) {
|
|
await Future.delayed(Duration(milliseconds: 10 + random.nextInt(20)));
|
|
_currentAiResponse = response.substring(0, i + 1);
|
|
notifyListeners();
|
|
}
|
|
|
|
// Add the complete message
|
|
final aiMessage = Message(
|
|
id: DateTime.now().millisecondsSinceEpoch.toString(),
|
|
content: response,
|
|
isUser: false,
|
|
);
|
|
_messages.add(aiMessage);
|
|
_isTyping = false;
|
|
_currentAiResponse = '';
|
|
notifyListeners();
|
|
}
|
|
|
|
void clearMessages() {
|
|
_messages.clear();
|
|
notifyListeners();
|
|
}
|
|
}
|