1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
|
// lib/features/chat/presentation/chat_screen.dart
import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
class ChatMessage {
final String role; // 'user' or 'assistant'
final String content;
final DateTime timestamp;
final String? imagePath; // 用户发送的图片
ChatMessage({
required this.role,
required this.content,
DateTime? timestamp,
this.imagePath,
}) : timestamp = timestamp ?? DateTime.now();
}
class ChatScreen extends ConsumerStatefulWidget {
final String? initialBirdSpecies;
const ChatScreen({super.key, this.initialBirdSpecies});
@override
ConsumerState<ChatScreen> createState() => _ChatScreenState();
}
class _ChatScreenState extends ConsumerState<ChatScreen> {
final TextEditingController _controller = TextEditingController();
final ScrollController _scrollController = ScrollController();
List<ChatMessage> _messages = [];
bool _isLoading = false;
@override
void initState() {
super.initState();
// 如果有初始鸟类信息,自动发送欢迎消息
if (widget.initialBirdSpecies != null) {
_messages.add(ChatMessage(
role: 'assistant',
content: '你好!我看到你拍到了一只${widget.initialBirdSpecies},'
'想了解什么?可以问我关于它的习性、分布、保护级别等问题。',
));
}
}
Future<void> _sendMessage() async {
final text = _controller.text.trim();
if (text.isEmpty) return;
setState(() {
_messages.add(ChatMessage(role: 'user', content: text));
_controller.clear();
_isLoading = true;
});
_scrollToBottom();
try {
// 构建对话上下文
final conversationHistory = _messages.map((m) => {
'role': m.role,
'content': m.content,
}).toList();
final response = await ref.read(
chatServiceProvider({
'messages': conversationHistory,
'context': widget.initialBirdSpecies ?? '',
}).future,
);
setState(() {
_messages.add(ChatMessage(role: 'assistant', content: response));
_isLoading = false;
});
} catch (e) {
setState(() {
_messages.add(ChatMessage(
role: 'assistant',
content: '抱歉,我暂时无法回答这个问题。请稍后再试。',
));
_isLoading = false;
});
}
_scrollToBottom();
}
void _scrollToBottom() {
WidgetsBinding.instance.addPostFrameCallback((_) {
if (_scrollController.hasClients) {
_scrollController.animateTo(
_scrollController.position.maxScrollExtent,
duration: const Duration(milliseconds: 300),
curve: Curves.easeOut,
);
}
});
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text('🐦 观鸟助手'),
backgroundColor: const Color(0xFF2E7D32),
actions: [
IconButton(
icon: const Icon(Icons.info_outline),
onPressed: () => _showBirdInfo(),
),
],
),
body: Column(
children: [
// 消息列表
Expanded(
child: ListView.builder(
controller: _scrollController,
padding: const EdgeInsets.all(16),
itemCount: _messages.length + (_isLoading ? 1 : 0),
itemBuilder: (context, index) {
if (index == _messages.length) {
return const _TypingIndicator();
}
return _MessageBubble(message: _messages[index]);
},
),
),
// 输入栏
Container(
padding: const EdgeInsets.all(8),
decoration: BoxDecoration(
color: Colors.white,
boxShadow: [
BoxShadow(
color: Colors.black12,
blurRadius: 4,
offset: const Offset(0, -2),
),
],
),
child: SafeArea(
child: Row(
children: [
// 图片按钮
IconButton(
icon: const Icon(Icons.image, color: Color(0xFF2E7D32)),
onPressed: () => _sendImage(),
),
// 输入框
Expanded(
child: TextField(
controller: _controller,
decoration: InputDecoration(
hintText: '问我关于鸟类的问题...',
border: OutlineInputBorder(
borderRadius: BorderRadius.circular(24),
borderSide: BorderSide.none,
),
filled: true,
fillColor: Colors.grey[100],
contentPadding: const EdgeInsets.symmetric(
horizontal: 16, vertical: 10),
),
maxLines: null,
textInputAction: TextInputAction.send,
onSubmitted: (_) => _sendMessage(),
),
),
// 发送按钮
IconButton(
icon: const Icon(Icons.send, color: Color(0xFF2E7D32)),
onPressed: _isLoading ? null : _sendMessage,
),
],
),
),
),
],
),
);
}
}
/// 消息气泡组件
class _MessageBubble extends StatelessWidget {
final ChatMessage message;
const _MessageBubble({required this.message});
@override
Widget build(BuildContext context) {
final isUser = message.role == 'user';
return Padding(
padding: const EdgeInsets.symmetric(vertical: 4),
child: Row(
mainAxisAlignment: isUser
? MainAxisAlignment.end
: MainAxisAlignment.start,
crossAxisAlignment: CrossAxisAlignment.start,
children: [
if (!isUser) ...[
const CircleAvatar(
backgroundColor: Color(0xFF2E7D32),
child: Text('🐦', style: TextStyle(fontSize: 20)),
),
const SizedBox(width: 8),
],
Flexible(
child: Container(
padding: const EdgeInsets.all(12),
decoration: BoxDecoration(
color: isUser
? const Color(0xFF2E7D32)
: Colors.grey[100],
borderRadius: BorderRadius.only(
topLeft: const Radius.circular(16),
topRight: const Radius.circular(16),
bottomLeft: Radius.circular(isUser ? 16 : 4),
bottomRight: Radius.circular(isUser ? 4 : 16),
),
),
child: Text(
message.content,
style: TextStyle(
color: isUser ? Colors.white : Colors.black87,
fontSize: 15,
),
),
),
),
if (isUser) const SizedBox(width: 8),
],
),
);
}
}
|