-
Notifications
You must be signed in to change notification settings - Fork 23
/
open_channel_page.dart
408 lines (361 loc) · 11.7 KB
/
open_channel_page.dart
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
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
// Copyright (c) 2023 Sendbird, Inc. All rights reserved.
import 'dart:async';
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:scrollable_positioned_list/scrollable_positioned_list.dart';
import 'package:sendbird_chat_sample/component/widgets.dart';
import 'package:sendbird_chat_sdk/sendbird_chat_sdk.dart';
class OpenChannelPage extends StatefulWidget {
const OpenChannelPage({Key? key}) : super(key: key);
@override
State<OpenChannelPage> createState() => OpenChannelPageState();
}
class OpenChannelPageState extends State<OpenChannelPage> {
final channelUrl = Get.parameters['channel_url']!;
final itemScrollController = ItemScrollController();
final textEditingController = TextEditingController();
late PreviousMessageListQuery query;
String title = '';
bool hasPrevious = false;
List<BaseMessage> messageList = [];
int? participantCount;
OpenChannel? openChannel;
@override
void initState() {
super.initState();
SendbirdChat.addChannelHandler('OpenChannel', MyOpenChannelHandler(this));
SendbirdChat.addConnectionHandler('OpenChannel', MyConnectionHandler(this));
OpenChannel.getChannel(channelUrl).then((openChannel) {
this.openChannel = openChannel;
openChannel.enter().then((_) => _initialize());
});
}
void _initialize() {
OpenChannel.getChannel(channelUrl).then((openChannel) {
query = PreviousMessageListQuery(
channelType: ChannelType.open,
channelUrl: channelUrl,
)..next().then((messages) {
setState(() {
messageList
..clear()
..addAll(messages);
title = '${openChannel.name} (${messageList.length})';
hasPrevious = query.hasNext;
participantCount = openChannel.participantCount;
});
});
});
}
@override
void dispose() {
SendbirdChat.removeChannelHandler('OpenChannel');
SendbirdChat.removeConnectionHandler('OpenChannel');
textEditingController.dispose();
OpenChannel.getChannel(channelUrl).then((channel) => channel.exit());
super.dispose();
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Widgets.pageTitle(title, maxLines: 2),
actions: const [],
),
body: Column(
children: [
participantCount != null ? _participantIdBox() : Container(),
hasPrevious ? _previousButton() : Container(),
Expanded(child: messageList.isNotEmpty ? _list() : Container()),
_messageSender(),
],
),
);
}
Widget _participantIdBox() {
return Column(
children: [
Padding(
padding: const EdgeInsets.all(8.0),
child: Row(
children: [
const Icon(Icons.person, size: 16.0),
Text(
participantCount.toString(),
textAlign: TextAlign.left,
style: const TextStyle(fontSize: 12.0, color: Colors.green),
),
],
),
),
const Divider(height: 1),
],
);
}
Widget _previousButton() {
return Container(
width: double.maxFinite,
height: 32.0,
color: Colors.purple[200],
child: IconButton(
icon: const Icon(Icons.expand_less, size: 16.0),
color: Colors.white,
onPressed: () async {
if (query.hasNext && !query.isLoading) {
final messages = await query.next();
final openChannel = await OpenChannel.getChannel(channelUrl);
setState(() {
messageList.insertAll(0, messages);
title = '${openChannel.name} (${messageList.length})';
hasPrevious = query.hasNext;
});
_scroll(0);
}
},
),
);
}
Widget _list() {
return ScrollablePositionedList.builder(
physics: const ClampingScrollPhysics(),
initialScrollIndex: messageList.length - 1,
itemScrollController: itemScrollController,
itemCount: messageList.length,
itemBuilder: (BuildContext context, int index) {
if (index >= messageList.length) return Container();
BaseMessage message = messageList[index];
return GestureDetector(
onDoubleTap: () async {
final openChannel = await OpenChannel.getChannel(channelUrl);
Get.toNamed(
'/message/update/${openChannel.channelType.toString()}/${openChannel.channelUrl}/${message.messageId}')
?.then((message) async {
if (message != null) {
for (int index = 0; index < messageList.length; index++) {
if (messageList[index].messageId == message.messageId) {
setState(() => messageList[index] = message);
break;
}
}
}
});
},
onLongPress: () async {
final openChannel = await OpenChannel.getChannel(channelUrl);
await openChannel.deleteMessage(message.messageId);
setState(() {
messageList.remove(message);
title = '${openChannel.name} (${messageList.length})';
});
},
child: Column(
children: [
ListTile(
title: Text(
message.message,
style: const TextStyle(
color: Colors.black,
fontWeight: FontWeight.bold,
),
),
subtitle: Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
Widgets.imageNetwork(
message.sender?.profileUrl, 16.0, Icons.account_circle),
Expanded(
child: Padding(
padding: const EdgeInsets.only(left: 4.0),
child: Text(
message.sender?.userId ?? '',
style: const TextStyle(fontSize: 12.0),
),
),
),
Container(
margin: const EdgeInsets.only(left: 16),
alignment: Alignment.centerRight,
child: Text(
DateTime.fromMillisecondsSinceEpoch(message.createdAt)
.toString(),
style: const TextStyle(fontSize: 12.0),
),
),
],
),
),
const Divider(height: 1),
],
),
);
},
);
}
Widget _messageSender() {
return Padding(
padding: const EdgeInsets.all(8.0),
child: Row(
children: [
Expanded(
child: Widgets.textField(textEditingController, 'Message'),
),
const SizedBox(width: 8.0),
ElevatedButton(
onPressed: () async {
if (textEditingController.value.text.isEmpty) {
return;
}
openChannel?.sendUserMessage(
UserMessageCreateParams(
message: textEditingController.value.text,
),
handler: (UserMessage message, SendbirdException? e) async {
if (e != null) {
await _showDialogToResendUserMessage(message);
} else {
_addMessage(message);
}
},
);
textEditingController.clear();
},
child: const Text('Send'),
),
],
),
);
}
Future<void> _showDialogToResendUserMessage(UserMessage message) async {
await showDialog(
context: context,
barrierDismissible: false,
builder: (context) {
return AlertDialog(
content: Text('Resend: ${message.message}'),
actions: [
TextButton(
onPressed: () {
openChannel?.resendUserMessage(
message,
handler: (message, e) async {
if (e != null) {
await _showDialogToResendUserMessage(message);
} else {
_addMessage(message);
}
},
);
Get.back();
},
child: const Text('Yes'),
),
TextButton(
onPressed: () {
Get.back();
},
child: const Text('No'),
),
],
);
});
}
void _addMessage(BaseMessage message) {
OpenChannel.getChannel(channelUrl).then((openChannel) {
setState(() {
messageList.add(message);
title = '${openChannel.name} (${messageList.length})';
participantCount = openChannel.participantCount;
});
Future.delayed(
const Duration(milliseconds: 100),
() => _scroll(messageList.length - 1),
);
});
}
void _updateMessage(BaseMessage message) {
OpenChannel.getChannel(channelUrl).then((openChannel) {
setState(() {
for (int index = 0; index < messageList.length; index++) {
if (messageList[index].messageId == message.messageId) {
messageList[index] = message;
break;
}
}
title = '${openChannel.name} (${messageList.length})';
participantCount = openChannel.participantCount;
});
});
}
void _deleteMessage(int messageId) {
OpenChannel.getChannel(channelUrl).then((openChannel) {
setState(() {
for (int index = 0; index < messageList.length; index++) {
if (messageList[index].messageId == messageId) {
messageList.removeAt(index);
break;
}
}
title = '${openChannel.name} (${messageList.length})';
participantCount = openChannel.participantCount;
});
});
}
void _updateParticipantCount() {
OpenChannel.getChannel(channelUrl).then((openChannel) {
setState(() {
participantCount = openChannel.participantCount;
});
});
}
void _scroll(int index) async {
if (messageList.length <= 1) return;
while (!itemScrollController.isAttached) {
await Future.delayed(const Duration(milliseconds: 1));
}
itemScrollController.scrollTo(
index: index,
duration: const Duration(milliseconds: 200),
curve: Curves.fastOutSlowIn,
);
}
}
class MyOpenChannelHandler extends OpenChannelHandler {
final OpenChannelPageState _state;
MyOpenChannelHandler(this._state);
@override
void onMessageReceived(BaseChannel channel, BaseMessage message) {
_state._addMessage(message);
}
@override
void onMessageUpdated(BaseChannel channel, BaseMessage message) {
_state._updateMessage(message);
}
@override
void onMessageDeleted(BaseChannel channel, int messageId) {
_state._deleteMessage(messageId);
}
@override
void onUserEntered(OpenChannel channel, User user) {
_state._updateParticipantCount();
}
@override
void onUserExited(OpenChannel channel, User user) {
_state._updateParticipantCount();
}
}
class MyConnectionHandler extends ConnectionHandler {
final OpenChannelPageState _state;
MyConnectionHandler(this._state);
@override
void onConnected(String userId) {}
@override
void onDisconnected(String userId) {}
@override
void onReconnectStarted() {}
@override
void onReconnectSucceeded() {
_state._initialize();
}
@override
void onReconnectFailed() {}
}