flutter/lib/IM/controller/chat_detail_controller.dart

94 lines
2.8 KiB
Dart
Raw Normal View History

2025-08-21 10:50:38 +08:00
import 'package:flutter/material.dart';
2025-07-21 15:46:30 +08:00
import 'package:get/get.dart';
import 'package:loopin/IM/im_message.dart';
import 'package:loopin/IM/im_service.dart';
import 'package:loopin/utils/index.dart';
import 'package:tencent_cloud_chat_sdk/models/v2_tim_message.dart';
class ChatDetailController extends GetxController {
final String userID;
ChatDetailController({required this.userID});
2025-08-21 10:50:38 +08:00
final ScrollController chatController = ScrollController();
2025-07-21 15:46:30 +08:00
final RxList<V2TimMessage> chatList = <V2TimMessage>[].obs;
2025-08-21 10:50:38 +08:00
final RxBool isFriend = true.obs;
2025-07-21 15:46:30 +08:00
void updateChatListWithTimeLabels(List<V2TimMessage> originMessages) async {
final idRes = await ImService.instance.selfUserId();
if (idRes.success) {
final selfUserId = idRes.data;
List<V2TimMessage> displayMessages = [];
for (int i = 0; i < originMessages.length; i++) {
final current = originMessages[i];
final currentTimestamp = current.timestamp ?? 0;
// 判断是否需要给当前这条消息加时间标签
bool needInsertLabel = false;
if (i == originMessages.length - 1) {
// 最后一条消息,加时间标签
needInsertLabel = true;
} else {
final next = originMessages[i + 1];
final nextTimestamp = next.timestamp ?? 0;
final diff = currentTimestamp - nextTimestamp;
if (diff > 180) {
needInsertLabel = true;
}
}
2025-08-21 10:50:38 +08:00
// if (i == 0) {
// // 第一条一定插时间
// needInsertLabel = true;
// } else {
// final prev = originMessages[i - 1];
// final prevTimestamp = prev.timestamp ?? 0;
// final diff = currentTimestamp - prevTimestamp;
2025-07-21 15:46:30 +08:00
2025-08-21 10:50:38 +08:00
// if (diff > 180) {
// needInsertLabel = true;
// }
// }
// 把当前消息先插入label后插入
displayMessages.add(current);
2025-07-21 15:46:30 +08:00
if (needInsertLabel) {
final labelTime = Utils().formatChatTime(currentTimestamp);
final timeLabel = await IMMessage().insertTimeLabel(labelTime, selfUserId);
displayMessages.add(timeLabel.data);
}
}
2025-08-21 10:50:38 +08:00
// 新加载的记录放在最上面
2025-07-21 15:46:30 +08:00
chatList.addAll(displayMessages);
}
}
2025-08-21 10:50:38 +08:00
///滚动
void scrollToBottom() {
if (chatController.hasClients) {
chatController.animateTo(
0,
duration: Duration(milliseconds: 200),
curve: Curves.easeOut,
);
}
// Future.delayed(Duration(milliseconds: 300), () {
// if (chatController.hasClients) {
// chatController.animateTo(
// chatController.position.maxScrollExtent,
// duration: Duration(milliseconds: 200),
// curve: Curves.easeOut,
// );
// }
// });
}
@override
void onClose() {
chatController.dispose();
super.onClose();
}
2025-07-21 15:46:30 +08:00
}