Initial commit: 91dj android client dev_1.0.0

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
谢宇宁
2026-10-08 11:37:25 +07:00
co-authored by Claude Opus 5.5
commit 97dd6a739a
1262 changed files with 119813 additions and 0 deletions
@@ -0,0 +1,283 @@
import 'package:flutter/material.dart';
import 'package:jydj/assets_tool/images.dart';
import 'package:jydj/im_manager/im_ad/im_ad_manager.dart';
import 'package:jydj/tools_base/banner/ads_item.dart';
import 'package:jydj/hj_utils/screen.dart';
import 'package:provider/provider.dart';
import '../../hj_model/splash/ads_model.dart';
import '../../tools_base/banner/ads_banner.dart';
import '../../tools_base/widget/card_swiper/src/swiper.dart';
import '../../tools_base/widget/net_image_widget.dart';
import '../../track_event_manager/track_manager.dart';
import '../im_ad/im_ad_item.dart';
import '../im_ad/im_ad_provider.dart';
import '../im_notification.dart';
class ImAdView extends StatefulWidget {
final String position;
final EdgeInsetsGeometry? padding;
final ImAdItem? adItem;
ImAdView({super.key, required this.position, this.padding, this.adItem});
@override
State<StatefulWidget> createState() {
return _ImAdViewState();
}
}
class _ImAdViewState extends State<ImAdView> {
bool _closeFloatAd = false;
List<ImAdItem> get adImList {
return ImAdProvider().adByPosition(widget.position)?.list ?? [];
}
List<AdsInfoModel> get advList {
return adImList.map((e) => e.covertAd).toList();
}
@override
Widget build(BuildContext context) {
return Consumer<ImAdProvider>(
builder: (context, provider, child) {
if (widget.position == ImAdManager.kPosChatFloatingGifBall) {
return _buildFloatStyle();
} else if (widget.position == ImAdManager.kPosListBanner) {
return _buildBannerStyle();
} else if (widget.position == ImAdManager.kPosListFeedNative) {
return _buildInsertCellStyle();
} else if (widget.position == ImAdManager.kPosChatNotificationBar) {
return _buildDetailTopStyle();
} else {
return SizedBox();
}
},
);
}
Widget _buildDetailTopStyle() {
if (_closeFloatAd) return SizedBox();
final List<ImAdItem> items = widget.adItem != null ? [widget.adItem!] : adImList;
if (items.isEmpty) return SizedBox();
return Container(
height: 68,
color: Color(0x1AE5365C),
padding: widget.padding ?? EdgeInsets.symmetric(horizontal: 12),
child: Row(
children: [
Expanded(
child: Swiper(
scrollDirection: Axis.vertical,
axisDirection: AxisDirection.down,
autoplay: items.length > 1,
autoplayDelay: 3000,
loop: items.length > 1,
itemCount: items.length,
itemBuilder: (context, index) {
final adImItem = items[index];
return AdsItem(
adInfo: adImItem.covertAd,
exposureModel: AdExposureModel(pageType: TrackEventPageType.imChatDetail, adType: AdType.smallIcon),
child: _buildDetailTopAdRow(adImItem),
);
},
),
),
2.sizeBoxW,
InkWell(
onTap: () {
_closeFloatAd = true;
setState(() {});
},
child: Container(
padding: EdgeInsets.fromLTRB(6, 4, 4, 6),
child: Image.asset("ad_close.png".commonImgPath, width: 10),
),
),
],
),
);
}
Widget _buildDetailTopAdRow(ImAdItem adImItem) {
return Row(
children: [
NetworkImageLoader(
imageUrl: adImItem.cover ?? "",
width: 48,
height: 48,
borderRadius: 48,
),
12.sizeBoxW,
Text(
adImItem.title ?? "",
maxLines: 1,
overflow: TextOverflow.ellipsis,
style: TextStyle(
fontSize: 16,
fontWeight: FontWeight.w500,
color: Colors.white.withValues(alpha: .9),
),
),
6.sizeBoxW,
Container(
padding: EdgeInsets.symmetric(horizontal: 6, vertical: 1),
decoration: BoxDecoration(
color: Colors.white.withValues(alpha: .1),
borderRadius: BorderRadius.circular(6),
),
child: Text(
"广告",
style: TextStyle(fontSize: 10, color: Colors.white.withValues(alpha: .9)),
),
),
Spacer(),
Container(
width: 48,
height: 24,
alignment: Alignment.center,
decoration: BoxDecoration(
color: Color(0xffFFC000),
borderRadius: BorderRadius.circular(24),
),
child: Text(
"领取",
style: TextStyle(fontSize: 12, color: Color(0xFFFFFFFF)),
),
),
],
);
}
Widget _buildInsertCellStyle() {
if (widget.adItem == null) return SizedBox();
bool isShowRed = ImAdProvider().isUnreadAd(widget.adItem!.id);
return AdsItem(
adInfo: widget.adItem!.covertAd,
exposureModel: AdExposureModel(pageType: TrackEventPageType.imChatDetail, adType: AdType.smallIcon),
onTap: () {
ImAdProvider().notifyClickAd(widget.adItem!.id);
ImMsgProvider().setUnReadStatusFromAd();
},
child: Container(
height: 68,
color: Color(0x1AE5365C),
padding: widget.padding ?? EdgeInsets.symmetric(horizontal: 12, vertical: 10),
child: Row(
children: [
NetworkImageLoader(
imageUrl: widget.adItem?.cover ?? "",
width: 48,
height: 48,
borderRadius: 48,
),
12.sizeBoxW,
Expanded(
child: Column(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Row(
children: [
Text(
widget.adItem?.title ?? "",
style: TextStyle(
fontSize: 16,
fontWeight: FontWeight.w500,
color: Colors.white,
),
),
if (isShowRed)
Container(
width: 10,
height: 10,
margin: EdgeInsets.only(bottom: 6, left: 4),
decoration: BoxDecoration(
color: Color(0xffF52C56),
borderRadius: BorderRadius.circular(10),
),
),
Spacer(),
Text(
"广告",
style: TextStyle(fontSize: 12, color: Colors.white.withValues(alpha: .55)),
),
],
),
Text(
"",
maxLines: 1,
style: TextStyle(fontSize: 14, color: Color(0x8CFFFFFF)),
),
],
),
),
],
),
),
);
}
Widget _buildBannerStyle() {
if (advList.isEmpty) return SizedBox();
return Container(
padding: widget.padding,
child: ClipRRect(
borderRadius: BorderRadius.circular(8),
child: AspectRatio(
aspectRatio: 720 / 150,
child: AdsBanner(
advList,
exposureModel: AdExposureModel(pageType: TrackEventPageType.imChatCenter, adType: AdType.banner),
),
),
),
);
}
Widget _buildFloatStyle() {
if (_closeFloatAd || advList.isEmpty) return SizedBox();
return SizedBox(
height: 60,
width: 60,
child: Stack(
alignment: Alignment.bottomLeft,
children: [
SizedBox(
height: 60,
width: 60,
child: Swiper(
index: 0,
autoplay: (adImList.length > 1),
autoplayDelay: 3000,
loop: adImList.length == 1 ? false : true,
itemBuilder: (BuildContext context, int index) {
ImAdItem adItem = adImList[index];
return AdsItem(
adInfo: adItem.covertAd,
showType: AdShowType.img,
borderRadius: 70,
exposureModel: AdExposureModel(pageType: TrackEventPageType.imChatDetail, adType: AdType.smallIcon),
);
},
itemCount: adImList.length,
),
),
Positioned(
top: 0,
right: 0,
child: InkWell(
onTap: () {
_closeFloatAd = true;
setState(() {});
},
child: Image.asset("ad_close.png".commonImgPath, width: 15),
),
),
],
),
);
}
}
@@ -0,0 +1,382 @@
import 'dart:async';
import 'dart:convert';
import 'dart:math';
import 'package:flutter/material.dart';
import 'package:flutter_mm_core/im_core.dart';
import 'package:get/get.dart';
import 'package:jydj/hj_model/user/wallet_model.dart';
import 'package:jydj/tools_base/debug_log.dart';
import 'package:jydj/tools_base/file_upload/file_upload_tool.dart';
import 'package:jydj/tools_base/file_upload/upload_result_model.dart';
import 'package:jydj/tools_base/global_store/store.dart';
import 'package:jydj/im_manager/api/im_api_service.dart';
import 'package:jydj/im_manager/chat_detail_page/widget/input_sheet_view.dart';
import 'package:jydj/im_manager/im_manager.dart';
import 'package:jydj/routers/jump_router.dart';
import 'package:jydj/tools_base/toast.dart';
import 'package:pull_to_refresh/pull_to_refresh.dart';
import '../im_notification.dart';
import '../model/im_message_resp.dart';
import '../model/im_user_model.dart';
enum IMConnectStatus {
isLoading,
success,
fail,
}
class ChatDetailLogic extends GetxController with WidgetsBindingObserver {
final int sessionId;
final String? peerAvatar;
ChatDetailLogic(this.sessionId, {this.peerAvatar});
/// 聊天页可见性(跨端契约 A5):
/// - 前台 + 页面在栈顶 → true(收到对端消息自动 markRead)
/// - 后台 / paused / inactive → false(不 markRead,未读累积)
bool _isPageVisible = true;
/// SDK 单聊会话主键格式:`${otherId}_${chatType}`(1v1 chatType=0)
String get _primaryId => '${sessionId}_0';
ModelUserInfo? imPeerModel; // IM服务用户信息
ImUserModel? peerUserModel; // 本地业务用户信息
IMConnectStatus imStatus = IMConnectStatus.isLoading;
List<IMMessageModel>? msgList;
// pullYsRefresh 内部创建并释放,这里仅持有引用用于翻页状态回调
RefreshController? refreshController;
final ScrollController scrollController = ScrollController();
TextEditingController textEditController = TextEditingController();
Rx<String?> selectedImagePath = Rx<String?>(null);
RxBool isSendingMsg = false.obs;
late StreamSubscription _subscription;
bool _hasNext = true; // 是否还有更早的历史消息
bool _isLoadingData = false; // 翻页加载中,防重复触发
WalletModel? get wallet => globalStore.wallet;
int get sendMsgPrice => globalStore.meInfo?.sendMsgPrice ?? 0;
@override
void didChangeAppLifecycleState(AppLifecycleState state) {
final wasVisible = _isPageVisible;
_isPageVisible = state == AppLifecycleState.resumed;
if (!wasVisible && _isPageVisible) {
// 后台 → 前台:补一次 markRead 同步累积的未读到服务端
_refreshConversationAndMarkRead();
}
}
@override
void onReady() {
globalStore.refreshWallet();
initImEvn();
_subscription = imEventBus.on<IMMsgEvent>(_receiveMsg);
scrollController.addListener(_scrollListener);
super.onReady();
}
// 滚动到距顶部半屏内时提前预加载更早消息,避免拉到边缘才触发的生硬感
void _scrollListener() {
if (!scrollController.hasClients) return;
final maxExtent = scrollController.position.maxScrollExtent;
final gapToTop = maxExtent - scrollController.offset;
if (maxExtent > 30 && _hasNext && gapToTop < Get.height / 2) {
loadMoreData();
}
}
void initImEvn() async {
var isConnect = await ImManager().connectServer();
if (isConnect == false) {
imStatus = IMConnectStatus.fail;
update();
return;
}
await _loadPeerImUserId();
await _loadMsgData();
_refreshConversationAndMarkRead();
imStatus = IMConnectStatus.success;
update();
}
Future<void> _loadPeerImUserId() async {
// 拉对方资料(imToken sdk 走 ImCore.getUserInfoById)
try {
imPeerModel = await ImCore.getUserInfoById(sessionId);
peerUserModel = await IMApiService.getImUserInfo(imUserId: sessionId);
} catch (e) {
debugLog('IM- loadPeerInfo:$e');
}
}
void _fillMessageAvatar(IMMessageModel model) {
if (model.fromSelf == true) {
model.senderNickName = globalStore.meInfo?.name;
model.senderAvatar = globalStore.meInfo?.portrait;
} else {
model.receiverNickName = imPeerModel?.name;
model.receiverAvatar = peerAvatar;
}
}
void refreshData() {
_loadMsgData();
}
void loadMoreData() {
if (msgList?.isNotEmpty == true) {
_loadMsgData(beforeTimestamp: msgList!.last.createdAt);
} else {
refreshController?.loadComplete();
}
}
Future _loadMsgData({int? beforeTimestamp, int size = 20}) async {
if (_isLoadingData) return;
_isLoadingData = true;
try {
List<ModelMessage> retList = await ImCore.loadMessages(
sessionId.toString(),
beforeTimestamp: beforeTimestamp,
limit: size,
);
debugLog(jsonEncode(retList
.map((m) => {
'chatMessageType': m.chatMessageType,
'senderID': m.senderID,
'receiverID': m.receiverID,
'content': m.content,
'extra': m.extra,
'sequence': m.sequence,
'isGroup': m.isGroup,
'timestamp': m.timestamp,
'readingStatus': m.readingStatus,
'recall': m.recall,
'url': m.url,
'localPath': m.localPath,
'size': m.size,
'width': m.width,
'height': m.height,
'length': m.length,
'thumbURL': m.thumbURL,
'messageState': m.messageState,
'messageId': m.messageId,
'localId': m.localId,
'quoteMsgId': m.quoteMsgId,
'quoteMsgState': m.quoteMsgState,
})
.toList()));
msgList ??= [];
if (beforeTimestamp == null) {
msgList?.clear();
}
var convertList = retList.map((e) => IMMessageModel.convertModel(e)).toList();
for (var model in convertList) {
_fillMessageAvatar(model);
}
msgList?.addAll(convertList);
if (retList.length == size) {
_hasNext = true;
refreshController?.loadComplete();
} else {
_hasNext = false;
refreshController?.loadNoData();
}
} catch (e) {
msgList ??= [];
debugLog(e);
refreshController?.loadComplete();
}
refreshController?.refreshCompleted();
_isLoadingData = false;
update();
}
Future readySendMsg({bool? isSend}) async {
if (isSend == true && (textEditController.text.isNotEmpty || selectedImagePath.value?.isNotEmpty == true)) {
// 点击发送按钮有内容,直接发送内容, 否则弹出输入框
sendMsgEvent();
} else {
final result = await Get.bottomSheet(
InputSheetView(
hint: sendMsgPrice > 0 ? "私信需要消费$sendMsgPrice金币" : "请输入内容",
textEditController: textEditController,
selectedImgPath: selectedImagePath.value,
imgCallback: (value) {
selectedImagePath.value = value;
},
),
backgroundColor: Colors.transparent,
barrierColor: Colors.transparent,
persistent: false,
isScrollControlled: true,
enableDrag: false,
settings: RouteSettings(name: 'im_chat_input'),
useRootNavigator: true,
);
update();
if (result == true) {
sendMsgEvent();
}
}
}
/// 发送消息(HTTP)。[directImagePath] 非空时为"选图即发":只发该图片,不读输入框/不动预览
/// 发送成功后消息由服务端回推,经 [_receiveMsg] 上屏(不做本地乐观插入)
Future sendMsgEvent({String? directImagePath}) async {
final bool isDirectImage = directImagePath?.isNotEmpty == true;
final String content = isDirectImage ? '' : textEditController.text;
final String? localImg = isDirectImage ? directImagePath : selectedImagePath.value;
if (content.isEmpty && localImg?.isNotEmpty != true) {
showToast("请输入消息内容");
return;
}
if (sendMsgPrice > (wallet?.amount ?? 0)) {
showToast("余额不足, 请先充值");
pushToWalletPage(tabPosition: 1);
return;
}
if (isSendingMsg.value) return;
isSendingMsg.value = true;
String? sendImagePath;
if (localImg?.isNotEmpty == true) {
try {
ImageUploadResultModel? imgResult = await FileUploadTool().uploadImage(localImg!);
sendImagePath = imgResult?.coverImg ?? "";
if (sendImagePath.isEmpty) {
isSendingMsg.value = false;
showToast("图片上传失败!");
return;
}
} catch (e) {
debugLog(e);
isSendingMsg.value = false;
showToast("图片上传失败!");
return;
}
}
if (peerUserModel?.userId == null) {
showToast("消息发送失败!");
isSendingMsg.value = false;
return;
}
try {
final bool isImageType = sendImagePath?.isNotEmpty == true;
final String textContent = content;
final resp = await IMApiService.sendPriLetter(
takeUid: peerUserModel!.userId!,
content: isImageType ? null : textContent,
imgUrl: isImageType ? [sendImagePath!] : null,
);
if (resp.isSuccess) {
if (!isDirectImage) {
textEditController.text = "";
selectedImagePath.value = null;
}
globalStore.refreshWallet(); // 扣费后刷新余额
if (textContent.isNotEmpty && isImageType) {
// 发送图片再发文本
await IMApiService.sendPriLetter(
takeUid: peerUserModel!.userId!,
content: textContent,
);
}
} else {
showToast(resp.toast.isNotEmpty ? resp.toast : "消息发送失败!");
}
} catch (e) {
debugLog('sendMsg: $e');
showToast("消息发送失败!");
}
isSendingMsg.value = false;
update();
}
void _receiveMsg(IMMsgEvent event) {
debugLog("IM-消息 --");
if (event.msgModel == null) return;
IMMessageModel msgModel = event.msgModel!;
if (msgModel.receiverId == sessionId.toString() || msgModel.senderId == sessionId.toString()) {
debugLog("当前聊天页面 发送/收到消息");
if (event.model!.messageState == 2) {
bool isExist = false;
if (msgModel.receiverId == sessionId.toString()) {
// 自己发的消息回推:防重(收到连续两次回调的情况)
for (int i = 0; i < min((msgList ?? []).length, 6); i++) {
if (msgList![i].messageId == msgModel.messageId) {
isExist = true;
}
}
}
if (!isExist) {
msgList ??= [];
_fillMessageAvatar(msgModel);
msgList!.insert(0, msgModel);
}
} else if (event.model!.messageState == 1) {
// 失败
} else {}
if (_isPageVisible) {
// A4:聊天页可见时收到对端消息自动 markRead,未读不累积
// A5:可见性门禁;后台/inactive 不主动 markRead,等回前台补一次
final seq = msgModel.seq ?? 0;
if (seq > 0) {
unawaited(_markConversationRead(seq: msgModel.seq ?? 0));
}
}
}
update();
}
// 发送会话通知,消息已读,取消会话红点
Future<void> _markConversationRead({required int seq}) async {
try {
await ImCore.setConversationRead(_primaryId);
} catch (e) {
debugLog('_markConversationRead local: $e');
}
if (seq <= 0) return;
try {
await ImCore.sendConversationRead(receiverId: sessionId, seq: seq);
} catch (e) {
debugLog('_markConversationRead server: $e');
}
}
Future<void> _refreshConversationAndMarkRead() async {
final c = await _fetchCurSession();
if (c == null) return;
await _markConversationRead(seq: c.seq);
}
Future<ModelConversation?> _fetchCurSession() async {
try {
ModelConversationListResult sessionRet = await ImCore.getConversations(
includeArchivedCount: false,
includeTotalUnreadCount: false,
);
for (final target in sessionRet.conversations) {
if (target.targetId == sessionId.toString()) {
return target;
}
}
} catch (e) {
debugLog('_fetchCurSession server: $e');
}
return null;
}
@override
void onClose() {
_subscription.cancel();
scrollController.removeListener(_scrollListener);
scrollController.dispose();
super.onClose();
}
}
@@ -0,0 +1,100 @@
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:jydj/tools_base/loading/loading_center_widget.dart';
import 'package:jydj/tools_base/refresh/pull_refresh.dart';
import 'package:jydj/im_manager/chat_detail_page/Im_ad_view.dart';
import 'package:jydj/im_manager/chat_detail_page/widget/input_foot_view.dart';
import 'package:jydj/im_manager/im_ad/im_ad_manager.dart';
import '../model/im_message_resp.dart';
import 'chat_detail_logic.dart';
import 'widget/chat_item_cell.dart';
class ChatDetailPage extends StatelessWidget {
final int imUserId; // IM 用户 id
final String? userName;
final int? uid; // 业务用户 uid
final String? peerAvatar; // 对方头像
const ChatDetailPage({
required this.imUserId,
required this.userName,
this.uid,
this.peerAvatar,
super.key,
});
@override
Widget build(BuildContext context) {
return GetBuilder<ChatDetailLogic>(
init: ChatDetailLogic(imUserId, peerAvatar: peerAvatar),
tag: "$imUserId",
builder: (logic) {
final peerUid = logic.peerUserModel?.userId ?? logic.peerUserModel?.peerId ?? uid;
return Scaffold(
appBar: AppBar(title: Text(userName ?? "")),
body: Stack(
children: [
if (logic.imStatus == IMConnectStatus.isLoading)
LoadingCenterWidget()
else if (logic.imStatus == IMConnectStatus.fail)
CErrorWidget(
errorMsg: "连接用户失败",
retryOnTap: () => logic.initImEvn(),
)
else
_buildContent(logic, peerUid),
Positioned(
right: 12,
bottom: 103,
child: ImAdView(position: ImAdManager.kPosChatFloatingGifBall),
),
],
),
);
},
);
}
Widget _buildContent(ChatDetailLogic logic, int? peerUid) {
return Column(
children: [
ImAdView(position: ImAdManager.kPosChatNotificationBar),
Expanded(
child: pullYsRefresh(
onInit: (ctr) => logic.refreshController = ctr,
enablePullDown: false,
enablePullUp: false, // 翻页靠滚动预加载,不用上拉 footer(避免顶部空一块)
child: ListView.builder(
controller: logic.scrollController,
itemCount: logic.msgList?.length ?? 0,
reverse: true,
padding: EdgeInsets.only(bottom: 12, top: 12),
itemBuilder: (context, index) {
IMMessageModel model = logic.msgList![index];
return ChatItemCell(model: model, peerUid: peerUid);
},
),
),
),
Obx(
() => InputFootView(
imagePath: logic.selectedImagePath.value,
isSendStatus: logic.isSendingMsg.value,
placeholder: logic.sendMsgPrice > 0 ? "私信需要消费${logic.sendMsgPrice}金币" : "请输入内容",
imgCallback: (value) {
logic.selectedImagePath.value = value;
},
onImageSend: (path) {
logic.sendMsgEvent(directImagePath: path);
},
begainCommentHandler: (value) {
logic.readySendMsg(isSend: value);
},
textEditController: logic.textEditController,
),
),
],
);
}
}
@@ -0,0 +1,94 @@
import 'dart:async';
import 'package:flutter_mm_core/im_core.dart';
import 'package:get/get.dart';
import 'package:jydj/tools_base/debug_log.dart';
import 'package:jydj/im_manager/im_ad/im_ad_manager.dart';
import 'package:jydj/im_manager/im_ad/im_ad_provider.dart';
import 'package:jydj/tools_base/toast.dart';
import '../im_manager.dart';
import '../model/im_message_resp.dart';
import 'chat_detail_logic.dart';
class ChatSessionListLogic extends GetxController {
ChatSessionListLogic();
List<IMSessionModel>? imSessionList;
IMConnectStatus imStatus = IMConnectStatus.isLoading;
@override
void onInit() {
ImCore.addConversationChangedListener(_listerIMConversation);
_loadData();
super.onInit();
}
void onInitData() {
imStatus = IMConnectStatus.isLoading;
imSessionList = null;
update();
_loadData();
}
Future _loadData() async {
try {
var isConnect = await ImManager().connectServer();
if (isConnect == false) {
imStatus = IMConnectStatus.fail;
showToast('消息连接失败,请稍后再试');
} else {
imStatus = IMConnectStatus.success;
ModelConversationListResult sessionRet = await ImCore.getConversations(
includeArchivedCount: false,
includeTotalUnreadCount: false,
);
imSessionList = IMSessionModel.covertData(sessionRet);
ImAdManager.insertAd(imSessionList, ImAdProvider().getAdList(ImAdManager.kPosListFeedNative));
}
} catch (e) {
debugLog(e);
}
imSessionList ??= [];
update();
}
void _listerIMConversation() {
debugLog("_listerIMConversation 变化");
unawaited(_loadData());
}
IMSessionModel? fetchSameSession(IMSessionModel info) {
for (IMSessionModel model in (imSessionList ?? [])) {
if (model.imUserId == info.imUserId) {
return model;
}
}
return null;
}
void skipToChatDetail(IMSessionModel sessionInfo) async {
await jumpToChatDetail(sessionInfo);
IMSessionModel? model = fetchSameSession(sessionInfo);
if (model != null) {
model.unreadCount = 0;
update();
_markConversationRead(sessionId: model.imUserId ?? 0);
}
}
// 发送会话通知,消息已读,取消会话红点
Future<void> _markConversationRead({required int sessionId}) async {
try {
await ImCore.setConversationRead("${sessionId}_0");
} catch (e) {
debugLog('iM- read1: $e');
}
}
@override
void onClose() {
ImCore.removeConversationChangedListener(_listerIMConversation);
super.onClose();
}
}
@@ -0,0 +1,135 @@
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:jydj/tools_base/loading/loading_center_widget.dart';
import 'package:jydj/tools_base/widget/net_image_widget.dart';
import 'package:jydj/im_manager/chat_detail_page/Im_ad_view.dart';
import 'package:jydj/hj_utils/screen.dart';
import '../im_ad/im_ad_manager.dart';
import '../model/im_message_resp.dart';
import 'chat_detail_logic.dart';
import 'chat_session_list_logic.dart';
class ChatSessionListView extends StatelessWidget {
final bool isSliverStyle;
const ChatSessionListView({
this.isSliverStyle = true,
super.key,
});
@override
Widget build(BuildContext context) {
return GetBuilder<ChatSessionListLogic>(
init: ChatSessionListLogic(),
builder: (logic) {
if (logic.imSessionList == null) {
return SliverToBoxAdapter(
child: SizedBox(
height: 300,
child: LoadingCenterWidget(),
),
);
} else if (logic.imStatus == IMConnectStatus.fail) {
return SliverToBoxAdapter(
child: CErrorWidget(
errorMsg: "消息连接失败",
retryOnTap: () => logic.onInitData(),
),
);
} else if (logic.imSessionList!.isEmpty) {
return SliverToBoxAdapter(
child: SizedBox(
height: 300,
child: CErrorWidget(),
),
);
} else {
return SliverList.builder(
itemCount: logic.imSessionList?.length ?? 0,
itemBuilder: (context, index) {
IMSessionModel model = logic.imSessionList![index];
if (model.isAdStyle) {
return ImAdView(
position: ImAdManager.kPosListFeedNative,
adItem: model.adItem,
);
} else {
return _buildItemInfo(logic, model);
}
},
);
}
},
);
}
Widget _buildItemInfo(ChatSessionListLogic logic, IMSessionModel sessionInfo) {
return GestureDetector(
onTap: () => logic.skipToChatDetail(sessionInfo),
child: Container(
height: 68,
color: Colors.transparent,
padding: EdgeInsets.symmetric(horizontal: 12, vertical: 10),
child: Row(
children: [
NetworkImageLoader(
imageUrl: sessionInfo.avatar ?? "",
width: 48,
height: 48,
borderRadius: 48,
),
12.sizeBoxW,
Expanded(
child: Column(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Row(
children: [
Text(
sessionInfo.nickName ?? "",
style: TextStyle(
fontSize: 16,
fontWeight: FontWeight.w500,
color: Colors.white,
),
),
if (sessionInfo.hasUnRead)
Container(
width: 10,
height: 10,
margin: EdgeInsets.only(bottom: 6, left: 4),
decoration: BoxDecoration(
color: Color(0xffF52C56),
borderRadius: BorderRadius.circular(10),
),
),
Spacer(),
Text(
sessionInfo.updatedYMD ?? "",
style: TextStyle(
fontSize: 12,
color:Color(0xff525252),
),
),
],
),
Text(
sessionInfo.messageType == 2 ? "[图片]" : sessionInfo.lastText ?? "",
maxLines: 1,
overflow: TextOverflow.ellipsis,
style: TextStyle(
fontSize: 14,
color: Color(0xff525252),
),
),
],
),
),
],
),
),
);
}
}
@@ -0,0 +1,234 @@
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:jydj/tools_base/global_store/store.dart';
import 'package:jydj/tools_base/widget/net_image_widget.dart';
import 'package:jydj/tools_base/widget/image_browser_page.dart';
import 'package:jydj/routers/jump_router.dart';
import '../../model/im_message_resp.dart';
class ChatItemCell extends StatefulWidget {
final IMMessageModel? model;
final VoidCallback? onResend;
final int? peerUid;
ChatItemCell({Key? key, this.model, this.onResend, this.peerUid}) : super(key: key);
@override
State<StatefulWidget> createState() {
return _ChatItemCellState();
}
}
class _ChatItemCellState extends State<ChatItemCell> {
bool get isImg => widget.model?.image?.isNotEmpty == true;
bool get isMe => widget.model?.fromSelf == true;
double imageWidth = 173;
void _showImageScan(String imageUrl) {
if (imageUrl.isNotEmpty) {
ImageBrowserPage.open([imageUrl]);
}
}
@override
Widget build(BuildContext context) {
if (isMe) {
return _buildRightStyle();
} else {
return _buildLeftStyle();
}
}
Widget _buildLeftStyle() {
return Container(
padding: EdgeInsets.fromLTRB(0, 12, 0, 6),
child: Column(
children: [
Container(
padding: EdgeInsets.fromLTRB(16, 0, 50, 0),
child: Row(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
GestureDetector(
onTap: () => _openProfile(widget.peerUid),
child: SizedBox(
width: 40,
height: 40,
child: NetworkImageLoader(
imageUrl: widget.model?.receiverAvatar ?? "",
width: 40,
height: 40,
borderRadius: 20,
),
),
),
SizedBox(width: 12),
Flexible(
child: Column(
mainAxisSize: MainAxisSize.max,
crossAxisAlignment: CrossAxisAlignment.start,
children: [
if (isImg)
InkWell(
onTap: () {
_showImageScan(widget.model?.image ?? "");
},
child: Container(
margin: EdgeInsets.only(top: 5),
alignment: Alignment.centerLeft,
constraints: BoxConstraints(maxWidth: 173),
child: _buildImageWidget(isLeft: true),
),
)
else
Container(
padding: EdgeInsets.symmetric(horizontal: 14, vertical: 10),
margin: EdgeInsets.only(top: 5),
decoration: BoxDecoration(
color: Colors.white.withValues(alpha: .05),
borderRadius: BorderRadius.only(
bottomLeft: Radius.circular(12),
bottomRight: Radius.circular(12),
topRight: Radius.circular(12),
topLeft: Radius.circular(2)),
),
child: Text(
widget.model?.content ?? "",
style: TextStyle(
color: Colors.white,
fontSize: 12,
),
),
),
],
),
),
],
),
),
],
),
);
}
Widget _buildRightStyle() {
return Container(
padding: EdgeInsets.fromLTRB(0, 12, 0, 6),
child: Column(
children: [
Container(
padding: EdgeInsets.fromLTRB(50, 0, 16, 0),
child: Row(
crossAxisAlignment: CrossAxisAlignment.center,
mainAxisAlignment: MainAxisAlignment.end,
children: [
_buildSendStatus(),
Flexible(
child: Column(
mainAxisSize: MainAxisSize.min,
crossAxisAlignment: CrossAxisAlignment.end,
children: [
if (isImg)
InkWell(
onTap: () {
_showImageScan(widget.model?.image ?? "");
},
child: Container(
margin: EdgeInsets.only(top: 5),
alignment: Alignment.centerRight,
constraints: BoxConstraints(maxWidth: 173),
child: _buildImageWidget(isLeft: false),
),
)
else
Container(
padding: EdgeInsets.symmetric(horizontal: 14, vertical: 10),
margin: EdgeInsets.only(top: 5),
decoration: BoxDecoration(
color: Color(0xff1DC194),
borderRadius: BorderRadius.only(
bottomLeft: Radius.circular(12),
bottomRight: Radius.circular(12),
topLeft: Radius.circular(12),
topRight: Radius.circular(4)),
),
child: Text(
widget.model?.content ?? "",
style: TextStyle(
color: Color(0xFF000000),
fontSize: 12,
),
),
),
],
),
),
SizedBox(width: 12),
GestureDetector(
onTap: () => _openProfile(globalStore.meInfo?.uid),
child: SizedBox(
width: 40,
height: 40,
child: NetworkImageLoader(
imageUrl: widget.model?.senderAvatar ?? "",
width: 40,
height: 40,
borderRadius: 20,
),
),
),
],
),
),
],
),
);
}
// 发送状态指示: 0发送中(菊花) 1失败(红色叹号,点击重发) 其余正常不展示
Widget _buildSendStatus() {
final state = widget.model?.messageState;
if (state == 0) {
return Padding(
padding: EdgeInsets.only(right: 8),
child: CupertinoActivityIndicator(radius: 8, color: Color(0xff999999)),
);
}
if (state == 1) {
return GestureDetector(
onTap: widget.onResend,
child: Padding(
padding: EdgeInsets.only(right: 8),
child: Icon(Icons.error, color: Color(0xffFF004F), size: 22),
),
);
}
return const SizedBox.shrink();
}
void _openProfile(int? uid) {
if (uid != null && uid > 0) {
pushToPersonCenter(uid);
}
}
Widget _buildImageWidget({bool isLeft = false}) {
return Stack(
children: [
NetworkImageLoader(
imageUrl: widget.model?.image ?? "",
width: imageWidth,
imgBorderRadius: BorderRadius.only(
bottomLeft: Radius.circular(12),
bottomRight: Radius.circular(12),
topRight: Radius.circular(isLeft ? 12 : 0),
topLeft: Radius.circular(isLeft ? 0 : 12),
),
),
],
);
}
}
@@ -0,0 +1,157 @@
import 'dart:io';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:jydj/assets_tool/images.dart';
import 'package:jydj/tools_base/widget/group_text_filed.dart';
import 'package:jydj/hj_utils/screen.dart';
import 'package:image_pickers/image_pickers.dart';
class InputFootView extends StatefulWidget {
final Function(bool) begainCommentHandler; // true 发送
final bool isSendStatus;
final TextEditingController textEditController;
final String? imagePath;
final Function(String?)? imgCallback;
final Function(String path)? onImageSend; // 选图即发:选完直接发送,不走底部预览
final String? placeholder;
const InputFootView({
super.key,
required this.begainCommentHandler,
this.isSendStatus = false,
required this.textEditController,
this.imagePath,
this.imgCallback,
this.onImageSend,
this.placeholder,
});
@override
State<InputFootView> createState() => _InputFootViewState();
}
class _InputFootViewState extends State<InputFootView> {
bool isImageSelectIng = false;
void choseImg() async {
isImageSelectIng = true;
final listMedia = await ImagePickers.pickerPaths(
uiConfig: UIConfig(uiThemeColor: Colors.white),
galleryMode: GalleryMode.image,
selectCount: 1,
showCamera: false,
);
if (listMedia.isNotEmpty) {
final ret = listMedia.map((e) => e.path ?? '').toList();
String selectedImgPath = ret.first;
if (selectedImgPath.isNotEmpty) {
// 选完图直接发送,不在底部预览
widget.onImageSend?.call(selectedImgPath);
}
}
setState(() {});
Future.delayed(Duration(milliseconds: 500), () {
isImageSelectIng = false;
});
}
@override
Widget build(BuildContext context) {
return SafeArea(
bottom: true,
child: Container(
color: const Color(0xff000000),
child: Container(
height: 58,
width: double.infinity,
margin: EdgeInsets.symmetric(vertical: 12.h, horizontal: 18.w),
child: Row(
children: [
Expanded(
child: GestureDetector(
onTap: () => widget.begainCommentHandler(false),
child: GroupTextFiled(
controller: widget.textEditController,
height: 32,
enabled: false,
padding: const EdgeInsets.symmetric(horizontal: 20),
textStyle: TextStyle(color: Colors.white, fontSize: 14.sp),
placeholder: widget.placeholder ?? '请输入消息',
placeholderTextStyle:
const TextStyle(color: Color(0xFF525252), fontSize: 12, fontWeight: FontWeight.w400),
decoration: BoxDecoration(
color: const Color(0x1AFFFFFF),
borderRadius: BorderRadius.circular(90),
),
),
),
),
Container(
margin: const EdgeInsets.only(left: 12),
child: Stack(
children: [
SizedBox(
height: 24,
width: 24,
child: GestureDetector(
onTap: choseImg,
child: widget.imagePath?.isNotEmpty == true
? ClipRRect(
borderRadius: BorderRadius.circular(4),
child: Image.file(
File(widget.imagePath!),
width: 24,
height: 24,
fit: BoxFit.cover,
),
)
: Image.asset("icon_pic.webp".commentPath),
),
),
if (widget.imagePath?.isNotEmpty == true)
Positioned(
top: 0,
right: 0,
child: GestureDetector(
onTap: () {
widget.imgCallback?.call(null);
setState(() {});
},
child: Image.asset(
"close_grey.png".commonImgPath,
width: 12,
height: 12,
),
),
),
],
),
),
10.sizeBoxW,
_buildSendButton(),
],
),
),
),
);
}
Widget _buildSendButton() {
return GestureDetector(
onTap: () {
widget.begainCommentHandler(true);
},
child: SizedBox(
width: 28,
height: 28,
child: widget.isSendStatus
? const CupertinoActivityIndicator(
color: Colors.redAccent,
radius: 12,
)
: Image.asset('ic_send.webp'.commentPath, width: 28, height: 28),
),
);
}
}
@@ -0,0 +1,166 @@
import 'dart:io';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get.dart';
import 'package:jydj/assets_tool/images.dart';
import 'package:jydj/tools_base/widget/group_text_filed.dart';
import 'package:jydj/hj_utils/screen.dart';
import 'package:image_pickers/image_pickers.dart';
class InputSheetView extends StatefulWidget {
final String? hint;
final TextEditingController textEditController;
final String? selectedImgPath;
final Function(String? imgPath)? imgCallback;
const InputSheetView({
super.key,
this.hint,
required this.textEditController,
this.selectedImgPath,
this.imgCallback,
});
@override
State<InputSheetView> createState() => _InputSheetViewState();
}
class _InputSheetViewState extends State<InputSheetView> with WidgetsBindingObserver {
final focus = FocusNode();
TextEditingController get textEditController => widget.textEditController;
bool hasShowKeyboard = false;
bool isImageSelectIng = false;
String? selectedImgPath;
@override
void initState() {
super.initState();
selectedImgPath = widget.selectedImgPath;
textEditController.addListener(() {
if (mounted) setState(() {});
});
WidgetsBinding.instance.addPostFrameCallback((timeStamp) {
focus.requestFocus();
});
WidgetsBinding.instance.addObserver(this);
}
void choseImg() async {
isImageSelectIng = true;
final listMedia = await ImagePickers.pickerPaths(
uiConfig: UIConfig(uiThemeColor: Colors.white),
galleryMode: GalleryMode.image,
selectCount: 1,
showCamera: false,
);
if (listMedia.isNotEmpty) {
final ret = listMedia.map((e) => e.path ?? '').toList();
selectedImgPath = ret.first;
widget.imgCallback?.call(selectedImgPath!);
}
setState(() {});
Future.delayed(Duration(milliseconds: 500), () {
isImageSelectIng = false;
});
}
@override
Widget build(BuildContext context) {
// 固定输入栏高度,避免 bottomSheet 占满屏幕产生蒙层
return Material(
color: const Color(0xff000000),
child: Container(
height: 58,
width: double.infinity,
margin: EdgeInsets.symmetric(vertical: 12.h, horizontal: 18.w),
child: Row(
children: [
Expanded(
child: GestureDetector(
onTap: () {
focus.requestFocus();
},
child: GroupTextFiled(
focusNode: focus,
controller: widget.textEditController,
height: 32,
padding: const EdgeInsets.symmetric(horizontal: 20),
textStyle: TextStyle(color: Colors.white, fontSize: 14.sp),
placeholder: widget.hint ?? '请输入消息',
placeholderTextStyle:
const TextStyle(color: Color(0xFF525252), fontSize: 12, fontWeight: FontWeight.w400),
decoration: BoxDecoration(
color: const Color(0x1AFFFFFF),
borderRadius: BorderRadius.circular(90),
),
),
),
),
Container(
margin: const EdgeInsets.only(left: 12),
child: Stack(
children: [
SizedBox(
height: 24,
width: 24,
child: GestureDetector(
onTap: choseImg,
child: selectedImgPath?.isNotEmpty == true
? ClipRRect(
borderRadius: BorderRadius.circular(4),
child: Image.file(
File(selectedImgPath!),
width: 24,
height: 24,
fit: BoxFit.cover,
),
)
: Image.asset("icon_pic.webp".commentPath),
),
),
if (selectedImgPath?.isNotEmpty == true)
Positioned(
top: 0,
right: 0,
child: GestureDetector(
onTap: () {
widget.imgCallback?.call(null);
setState(() {});
},
child: Image.asset(
"close_grey.png".commonImgPath,
width: 12,
height: 12,
),
),
),
],
),
),
10.sizeBoxW,
_buildSendButton(),
],
),
),
);
}
Widget _buildSendButton() {
return GestureDetector(
onTap: () {
focus.unfocus();
Get.back(result: true);
},
child: Image.asset('ic_send.webp'.commentPath, width: 28, height: 28),
);
}
@override
void dispose() {
focus.unfocus();
WidgetsBinding.instance.removeObserver(this);
super.dispose();
}
}