diff --git a/lib/controller/message/chat_controller.dart b/lib/controller/message/chat_controller.dart index dc40ac2..cb69b67 100644 --- a/lib/controller/message/chat_controller.dart +++ b/lib/controller/message/chat_controller.dart @@ -3,6 +3,7 @@ import 'package:flutter_smart_dialog/flutter_smart_dialog.dart'; import 'dart:convert'; import '../../im/im_manager.dart'; +import '../../model/home/marriage_data.dart'; import 'package:im_flutter_sdk/im_flutter_sdk.dart'; import 'conversation_controller.dart'; @@ -12,6 +13,13 @@ class ChatController extends GetxController { // 用户信息 final Rx userInfo = Rx(null); + // 外部传入的用户数据模型(用于在获取不到环信用户信息时使用) + MarriageData? _userData; + + // 外部传入的用户信息(用于在获取不到环信用户信息时使用) + String? _externalNickName; + String? _externalAvatarUrl; + // 消息列表 final RxList messages = RxList([]); @@ -22,7 +30,20 @@ class ChatController extends GetxController { final RxBool isSendingVideo = RxBool(false); final RxString sendingStatus = RxString(''); - ChatController({required this.userId}); + ChatController({ + required this.userId, + MarriageData? userData, + }) { + // 如果构造函数传入了用户数据模型,保存并使用 + if (userData != null) { + _userData = userData; + _externalNickName = userData.nickName; + _externalAvatarUrl = userData.profilePhoto; + } + } + + /// 获取用户数据模型 + MarriageData? get userData => _userData; @override void onInit() { @@ -32,6 +53,10 @@ class ChatController extends GetxController { // 初始化时获取用户信息和消息列表 fetchUserInfo(); fetchMessages(); + // 如果有外部传入的用户信息,触发 UI 更新 + if (_externalNickName != null || _externalAvatarUrl != null) { + update(); + } } @override @@ -52,17 +77,64 @@ class ChatController extends GetxController { Get.log('获取用户信息成功: ${info.nickName}'); } } else { - if (Get.isLogEnable) { - Get.log('未找到用户信息: $userId'); + // 如果没有获取到用户信息,但 userInfo 已经有值(从外部设置的),则不覆盖 + if (userInfo.value == null) { + if (Get.isLogEnable) { + Get.log('未找到用户信息: $userId,使用外部传入的信息'); + } + // 即使没有从环信获取到用户信息,也触发 UI 更新,因为外部可能传入了信息 + update(); } } } catch (e) { if (Get.isLogEnable) { - Get.log('获取用户信息失败: $e'); + Get.log('获取用户信息失败: $e,使用外部传入的信息'); + } + // 即使获取失败,也触发 UI 更新 + update(); + } + } + + /// 从外部设置用户信息(用于从其他页面传递用户数据) + void setUserInfoFromExternal({String? nickName, String? avatarUrl}) { + try { + // 保存外部传入的用户信息 + _externalNickName = nickName; + _externalAvatarUrl = avatarUrl; + + // 如果当前没有用户信息,尝试从服务器获取 + if (userInfo.value == null) { + fetchUserInfo().then((_) { + // 如果获取后还是没有用户信息,触发 UI 更新以使用外部传入的信息 + if (userInfo.value == null) { + update(); + } + }); + } + + // 触发 UI 更新,使外部传入的信息生效 + update(); + + if (Get.isLogEnable) { + Get.log('设置外部用户信息: nickName=$nickName, avatarUrl=$avatarUrl'); + } + } catch (e) { + if (Get.isLogEnable) { + Get.log('设置用户信息失败: $e'); } } } + /// 获取用户昵称(优先使用环信用户信息,如果没有则使用外部传入的) + String? get userNickName { + return userInfo.value?.nickName ?? _externalNickName; + } + + /// 获取用户头像(优先使用环信用户信息,如果没有则使用外部传入的) + String? get userAvatarUrl { + return userInfo.value?.avatarUrl ?? _externalAvatarUrl; + } + /// 发送消息 Future sendMessage(String content) async { EMMessage? tempMessage; diff --git a/lib/controller/message/conversation_controller.dart b/lib/controller/message/conversation_controller.dart index 2e3a05e..3abc6c6 100644 --- a/lib/controller/message/conversation_controller.dart +++ b/lib/controller/message/conversation_controller.dart @@ -1,5 +1,4 @@ import 'package:get/get.dart'; -import 'package:get_storage/get_storage.dart'; import 'package:im_flutter_sdk/im_flutter_sdk.dart'; import '../../im/im_manager.dart'; @@ -109,9 +108,25 @@ class ConversationController extends GetxController { return '${messageTime.month.toString().padLeft(2, '0')}-${messageTime.day.toString().padLeft(2, '0')}'; } - Future loadContact(String userId) async{ - var data = await IMManager.instance.getContacts(userId); - return data[userId]!; + Future loadContact(String userId) async{ + try { + var data = await IMManager.instance.getContacts(userId); + final userInfo = data[userId]; + + // 如果获取不到用户信息,返回 null + if (userInfo == null) { + if (Get.isLogEnable) { + Get.log('⚠️ [ConversationController] 未获取到用户信息: $userId'); + } + } + + return userInfo; + } catch (e) { + if (Get.isLogEnable) { + Get.log('❌ [ConversationController] 获取用户信息失败: $userId, 错误: $e'); + } + return null; + } } Future lastMessage(EMConversation conversation) async{ diff --git a/lib/im/im_manager.dart b/lib/im/im_manager.dart index 5265fe8..d465192 100644 --- a/lib/im/im_manager.dart +++ b/lib/im/im_manager.dart @@ -171,7 +171,6 @@ class IMManager { String content, String toChatUsername, ) async { - print('Text message sent'); try { // 创建文本消息 final message = EMMessage.createTxtSendMessage( @@ -179,10 +178,23 @@ class IMManager { content: content, ); - print('Text message sent successfully'); - return await EMClient.getInstance.chatManager.sendMessage(message); + // 发送消息(如果未登录会抛出异常) + final sentMessage = await EMClient.getInstance.chatManager.sendMessage(message); + + if (Get.isLogEnable) { + Get.log('✅ [IMManager] 文本消息发送成功: to=$toChatUsername, content=$content'); + } else { + print('✅ [IMManager] 文本消息发送成功: to=$toChatUsername, content=$content'); + } + + return sentMessage; } catch (e) { - print('Failed to send text message: $e'); + // 捕获异常,可能是未登录或其他错误 + if (Get.isLogEnable) { + Get.log('❌ [IMManager] 发送文本消息失败: to=$toChatUsername, 错误: $e'); + } else { + print('❌ [IMManager] 发送文本消息失败: to=$toChatUsername, 错误: $e'); + } return null; } } diff --git a/lib/pages/home/user_information_page.dart b/lib/pages/home/user_information_page.dart index ee8e7fb..18e6273 100644 --- a/lib/pages/home/user_information_page.dart +++ b/lib/pages/home/user_information_page.dart @@ -2,6 +2,7 @@ import 'package:dating_touchme_app/controller/global.dart'; import 'package:dating_touchme_app/generated/assets.dart'; import 'package:dating_touchme_app/model/home/marriage_data.dart'; import 'package:dating_touchme_app/pages/home/report_page.dart'; +import 'package:dating_touchme_app/pages/message/chat_page.dart'; import 'package:flutter/material.dart'; import 'package:flutter_screenutil/flutter_screenutil.dart'; import 'package:get/get.dart'; @@ -272,31 +273,40 @@ class _UserInformationPageState extends State { Row( mainAxisAlignment: MainAxisAlignment.spaceBetween, children: [ - Container( - width: 246.w, - height: 38.w, - decoration: BoxDecoration( - borderRadius: BorderRadius.all(Radius.circular(38.w)), - color: const Color.fromRGBO(51, 51, 51, 1) - ), - child: Row( - mainAxisAlignment: MainAxisAlignment.center, - children: [ - Image.asset( - Assets.imagesChatBtn, - width: 13.w, - height: 12.w, - ), - SizedBox(width: 4.w,), - Text( - "发消息", - style: TextStyle( - fontSize: 15.w, - color: Colors.white, - fontWeight: FontWeight.w500 + InkWell( + onTap: () { + // 跳转到聊天页面,传递用户ID和用户数据模型 + Get.to(() => ChatPage( + userId: widget.userData.userId, + userData: widget.userData, + )); + }, + child: Container( + width: 246.w, + height: 38.w, + decoration: BoxDecoration( + borderRadius: BorderRadius.all(Radius.circular(38.w)), + color: const Color.fromRGBO(51, 51, 51, 1) + ), + child: Row( + mainAxisAlignment: MainAxisAlignment.center, + children: [ + Image.asset( + Assets.imagesChatBtn, + width: 13.w, + height: 12.w, ), - ) - ], + SizedBox(width: 4.w,), + Text( + "发消息", + style: TextStyle( + fontSize: 15.w, + color: Colors.white, + fontWeight: FontWeight.w500 + ), + ) + ], + ), ), ), Container( diff --git a/lib/pages/message/chat_page.dart b/lib/pages/message/chat_page.dart index f7b9f67..71c7276 100644 --- a/lib/pages/message/chat_page.dart +++ b/lib/pages/message/chat_page.dart @@ -8,14 +8,20 @@ import '../../controller/message/chat_controller.dart'; import '../../controller/message/voice_player_manager.dart'; // import '../../controller/message/call_manager.dart'; // 暂时注释 import '../../generated/assets.dart'; +import '../../model/home/marriage_data.dart'; import '../../../widget/message/chat_input_bar.dart'; import '../../../widget/message/message_item.dart'; import 'chat_settings_page.dart'; class ChatPage extends StatefulWidget { - final String userId; + final String userId; // 对应 MarriageData.userId + final MarriageData? userData; // 可选:从外部传入的用户数据模型 - const ChatPage({required this.userId, super.key}); + const ChatPage({ + required this.userId, + this.userData, + super.key, + }); @override State createState() => _ChatPageState(); @@ -29,8 +35,19 @@ class _ChatPageState extends State { @override void initState() { super.initState(); - // 初始化 controller - _controller = Get.put(ChatController(userId: widget.userId)); + // 初始化 controller,直接传入用户信息参数 + // 如果已存在相同 userId 的 controller,先删除再创建新的,确保参数正确 + final tag = 'chat_${widget.userId}'; + if (Get.isRegistered(tag: tag)) { + Get.delete(tag: tag); + } + _controller = Get.put( + ChatController( + userId: widget.userId, + userData: widget.userData, + ), + tag: tag, + ); // 监听滚动,当滚动到顶部时加载更多消息 _scrollController.addListener(() { @@ -79,7 +96,7 @@ class _ChatPageState extends State { child: Scaffold( backgroundColor: Color(0xffF5F5F5), appBar: AppBar( - title: Text(controller.userInfo.value?.nickName ?? ''), + title: Text(controller.userNickName ?? widget.userData?.nickName ?? ''), centerTitle: true, actions: [ Container( @@ -124,7 +141,7 @@ class _ChatPageState extends State { itemBuilder: (context, index) { // 第一个是用户信息卡片 if (index == 0) { - return _buildUserInfoCard(controller); + return _buildUserInfoCard(controller, widget.userData); } final message = controller.messages[index - 1]; @@ -141,6 +158,7 @@ class _ChatPageState extends State { message: message, isSentByMe: isSentByMe, previousMessage: previousMessage, + chatController: controller, // 传递 controller 避免使用 Get.find ); }, ), @@ -204,55 +222,44 @@ class _ChatPageState extends State { } // 构建用户信息卡片 - Widget _buildUserInfoCard(ChatController controller) { - final userInfo = controller.userInfo.value; + Widget _buildUserInfoCard(ChatController controller, MarriageData? userData) { + // 优先使用传入的 MarriageData,如果没有则使用环信用户信息 + final marriageData = userData ?? _getMarriageDataFromController(controller); // 如果用户信息还未加载,显示占位符 - if (userInfo == null) { + if (marriageData == null) { return SizedBox.shrink(); } - return Container( - margin: EdgeInsets.only(bottom: 16.w), - decoration: BoxDecoration( - borderRadius: BorderRadius.circular(16.w), - ), - child: LayoutBuilder( - builder: (context, constraints) { - // 计算按710:351比例的高度 - // 宽度需要考虑 ListView 的 padding(左右各16.w) - final screenWidth = MediaQuery.of(context).size.width; - final availableWidth = screenWidth - 32.w; // 减去左右 padding - final width = availableWidth; - final height = width * (351 / 710); - return Container( - height: height, - decoration: BoxDecoration( - borderRadius: BorderRadius.circular(16.w), - image: DecorationImage( - image: AssetImage(Assets.imagesChatUserBg), - fit: BoxFit.cover, + return IntrinsicHeight( + child: Container( + margin: EdgeInsets.only(bottom: 16.w), + decoration: BoxDecoration( + borderRadius: BorderRadius.circular(16.w), + image: DecorationImage( + image: AssetImage(Assets.imagesChatUserBg), + fit: BoxFit.cover, + ), + ), + child: Stack( + children: [ + // 顶层背景图(chat_user_bg_bottom,覆盖整个卡片) + Positioned.fill( + child: ClipRRect( + borderRadius: BorderRadius.circular(16.w), + child: Image.asset( + Assets.imagesChatUserBgBottom, + fit: BoxFit.cover, // 覆盖整个区域,保持宽高比 + ), ), ), - child: Stack( - children: [ - // 顶层背景图(chat_user_bg_bottom,按710x351比例覆盖整个卡片) - Positioned.fill( - child: ClipRRect( - borderRadius: BorderRadius.circular(16.w), - child: Image.asset( - Assets.imagesChatUserBgBottom, - fit: BoxFit.cover, - ), - ), - ), - // 内容 - Padding( - padding: EdgeInsets.all(16.w), - child: Column( - mainAxisSize: MainAxisSize.min, - crossAxisAlignment: CrossAxisAlignment.start, - children: [ + // 内容(自适应高度) + Padding( + padding: EdgeInsets.all(16.w), + child: Column( + mainAxisSize: MainAxisSize.min, + crossAxisAlignment: CrossAxisAlignment.start, + children: [ // 头部:名称、标签、箭头 Row( crossAxisAlignment: CrossAxisAlignment.start, @@ -268,7 +275,7 @@ class _ChatPageState extends State { crossAxisAlignment: WrapCrossAlignment.center, children: [ Text( - userInfo.nickName ?? '用户', + marriageData.nickName, style: TextStyle( fontSize: 16.sp, fontWeight: FontWeight.w600, @@ -276,47 +283,48 @@ class _ChatPageState extends State { ), ), // 实名认证标签(和主页一样) - Container( - padding: EdgeInsets.symmetric( - horizontal: 8.w, - vertical: 2.h, - ), - decoration: BoxDecoration( - color: Color(0xFFF3E9FF), - borderRadius: BorderRadius.circular(12.w), - border: Border.all( - width: 1, - color: Color.fromRGBO(117, 98, 249, 0.32), + if (marriageData.isRealNameCertified) + Container( + padding: EdgeInsets.symmetric( + horizontal: 8.w, + vertical: 4.h, ), - ), - constraints: BoxConstraints( - minWidth: 40.w, - ), - child: Row( - mainAxisSize: MainAxisSize.min, - children: [ - Image.asset( - Assets.imagesVerifiedIcon, - width: 14.w, - height: 12.w, + decoration: BoxDecoration( + color: Color(0xFFF3E9FF), + borderRadius: BorderRadius.circular(12.w), + border: Border.all( + width: 1, + color: Color.fromRGBO(117, 98, 249, 0.32), ), - SizedBox(width: 4.w), - Text( - '实名', - style: TextStyle( - fontSize: 9.sp, - color: Color.fromRGBO(160, 92, 255, 1), - fontWeight: FontWeight.w500, + ), + constraints: BoxConstraints( + minWidth: 40.w, + ), + child: Row( + mainAxisSize: MainAxisSize.min, + children: [ + Image.asset( + Assets.imagesVerifiedIcon, + width: 14.w, + height: 12.w, ), - ), - ], + SizedBox(width: 4.w), + Text( + '实名', + style: TextStyle( + fontSize: 9.sp, + color: Color.fromRGBO(160, 92, 255, 1), + fontWeight: FontWeight.w500, + ), + ), + ], + ), ), - ), // 在线状态标签(和主页一样) Container( padding: EdgeInsets.symmetric( horizontal: 8.w, - vertical: 2.h, + vertical: 4.h, ), decoration: BoxDecoration( color: Color.fromRGBO(234, 255, 219, 1), @@ -338,10 +346,10 @@ class _ChatPageState extends State { ], ), SizedBox(height: 8.h), - // 用户信息:性别图标、年龄、位置、身高 + // 用户信息:性别图标、年龄、位置(根据 MarriageData 显示) Row( children: [ - // 性别图标(默认显示女性图标,可以根据实际数据调整) + // 性别图标(根据实际数据调整,这里暂时默认显示女性图标) Image.asset( Assets.imagesFemale, width: 14.w, @@ -349,28 +357,22 @@ class _ChatPageState extends State { ), SizedBox(width: 4.w), Text( - '19', + '${marriageData.age}', style: TextStyle( fontSize: 12.sp, color: Colors.grey[700], ), ), - SizedBox(width: 12.w), - Text( - '北京', - style: TextStyle( - fontSize: 12.sp, - color: Colors.grey[700], - ), - ), - SizedBox(width: 12.w), - Text( - '160cm', - style: TextStyle( - fontSize: 12.sp, - color: Colors.grey[700], + if (marriageData.cityName.isNotEmpty) ...[ + SizedBox(width: 12.w), + Text( + marriageData.cityName, + style: TextStyle( + fontSize: 12.sp, + color: Colors.grey[700], + ), ), - ), + ], ], ), ], @@ -394,48 +396,70 @@ class _ChatPageState extends State { ), SizedBox(height: 8.h), // 减小间距 // 个人简介(单行) - Text( - '喜欢在广州的早茶里抢最后一个虾饺,也能在深夜的猎德大桥...', - style: TextStyle( - fontSize: 13.sp, - color: Colors.grey[800], - height: 1.4, + if (marriageData.describeInfo.isNotEmpty) + Text( + marriageData.describeInfo, + style: TextStyle( + fontSize: 13.sp, + color: Colors.grey[800], + height: 1.4, + ), + maxLines: 1, + overflow: TextOverflow.ellipsis, ), - maxLines: 1, - overflow: TextOverflow.ellipsis, - ), - SizedBox(height: 8.h), // 减小间距 - // 图片画廊 - Row( - children: List.generate(4, (index) { - return Expanded( - child: Container( - margin: EdgeInsets.only( - right: index < 3 ? 8.w : 0, - ), - height: 50.w, // 进一步减小高度避免被裁剪 - decoration: BoxDecoration( - borderRadius: BorderRadius.circular(8.w), - image: DecorationImage( - image: AssetImage(Assets.imagesAvatarsExample), - fit: BoxFit.cover, + if (marriageData.photoList.isNotEmpty) ...[ + SizedBox(height: 8.h), // 图片上方间距 + // 图片画廊(正方形) + Row( + children: marriageData.photoList.take(4).toList().asMap().entries.map((entry) { + final index = entry.key; + final photo = entry.value; + final photoUrl = photo.photoUrl.trim().replaceAll('`', ''); // 移除URL中的反引号 + return Expanded( + child: AspectRatio( + aspectRatio: 1, // 设置为正方形 + child: Container( + margin: EdgeInsets.only( + right: index < 3 ? 8.w : 0, + ), + decoration: BoxDecoration( + borderRadius: BorderRadius.circular(8.w), + image: DecorationImage( + image: NetworkImage(photoUrl), + fit: BoxFit.cover, + onError: (exception, stackTrace) { + // 加载失败时显示占位图 + return; + }, + ), + ), ), ), - ), - ); - }), - ), - ], - ), - ), - ], + ); + }).toList(), + ), + SizedBox(height: 4.h), // 图片下方间距 + ], + ], + ), ), - ); - }, + ], + ), ), ); } + // 从 Controller 获取 MarriageData(如果没有传入) + MarriageData? _getMarriageDataFromController(ChatController controller) { + // 优先从 controller 获取已保存的 userData + if (controller.userData != null) { + return controller.userData; + } + + // 如果 controller 也没有,返回 null,不显示卡片 + return null; + } + // 加载更多消息 Future _loadMoreMessages() async { if (_isLoadingMore) return; diff --git a/lib/pages/message/conversation_tab.dart b/lib/pages/message/conversation_tab.dart index 9f3346c..7e2d965 100644 --- a/lib/pages/message/conversation_tab.dart +++ b/lib/pages/message/conversation_tab.dart @@ -44,16 +44,11 @@ class _ConversationTabState extends State ); } - // 即使列表为空也显示测试项 return ListView.builder( padding: const EdgeInsets.only(top: 8), - itemCount: controller.conversations.length + 1, // 添加测试项 + itemCount: controller.conversations.length, itemBuilder: (context, index) { - // 第一个是测试项 - if (index == 0) { - return _buildTestConversationItem(); - } - final conversation = controller.conversations[index - 1]; + final conversation = controller.conversations[index]; return _buildConversationItem(conversation); }, ); @@ -63,142 +58,9 @@ class _ConversationTabState extends State ); } - // 构建测试会话项 - Widget _buildTestConversationItem() { - final double screenWidth = MediaQuery.of(context).size.width; - final int testUnreadCount = 3; - final String testTime = controller.formatMessageTime( - DateTime.now().millisecondsSinceEpoch, - ); - - final Widget cellContent = Builder( - builder: (cellContext) => GestureDetector( - onTap: () { - TDSwipeCellInherited.of(cellContext)?.cellClick(); - // 跳转到聊天页面,使用测试用户ID - Get.to(ChatPage(userId: 'test_user_001')); - }, - child: Container( - padding: const EdgeInsets.symmetric( - horizontal: 16, - vertical: 12, - ), - decoration: const BoxDecoration( - color: Colors.white, - borderRadius: BorderRadius.all(Radius.circular(16)), - ), - margin: const EdgeInsets.only( - bottom: 8, - left: 16, - right: 16, - ), - child: Row( - crossAxisAlignment: CrossAxisAlignment.start, - children: [ - Container( - width: 56, - height: 56, - decoration: BoxDecoration( - borderRadius: BorderRadius.circular(28), - image: const DecorationImage( - image: AssetImage(Assets.imagesAvatarsExample), - fit: BoxFit.cover, - ), - ), - ), - const SizedBox(width: 12), - Expanded( - child: Column( - crossAxisAlignment: CrossAxisAlignment.start, - children: [ - Row( - mainAxisAlignment: MainAxisAlignment.spaceBetween, - crossAxisAlignment: CrossAxisAlignment.start, - children: [ - const Expanded( - child: Text( - '测试用户', - style: TextStyle( - fontSize: 16, - fontWeight: FontWeight.w500, - color: Colors.black, - ), - ), - ), - Text( - testTime, - style: const TextStyle( - fontSize: 12, - color: Colors.grey, - ), - ), - ], - ), - const SizedBox(height: 6), - Row( - crossAxisAlignment: CrossAxisAlignment.center, - children: [ - const Expanded( - child: Text( - '这是一条测试消息,用于调试', - style: TextStyle( - fontSize: 14, - color: Colors.grey, - ), - overflow: TextOverflow.ellipsis, - ), - ), - Container( - margin: const EdgeInsets.only(left: 8), - padding: const EdgeInsets.symmetric( - horizontal: 8, - vertical: 2, - ), - decoration: BoxDecoration( - color: Colors.red, - borderRadius: BorderRadius.circular(10), - ), - child: Text( - testUnreadCount.toString(), - style: const TextStyle( - fontSize: 12, - color: Colors.white, - ), - ), - ), - ], - ), - ], - ), - ), - ], - ), - ), - ), - ); - - return TDSwipeCell( - slidableKey: const ValueKey('test_conversation'), - groupTag: 'conversation_swipe_group', - right: TDSwipeCellPanel( - extentRatio: 72 / screenWidth, - children: [ - TDSwipeCellAction( - backgroundColor: TDTheme.of(context).errorColor6, - label: '删除', - onPressed: (actionContext) { - Get.snackbar('调试', '删除测试会话'); - }, - ), - ], - ), - cell: cellContent, - ); - } - // 构建会话项 Widget _buildConversationItem(EMConversation conversation) { - return FutureBuilder( + return FutureBuilder( future: controller.loadContact(conversation.id), builder: (context, userSnapshot) { final EMUserInfo? userInfo = userSnapshot.data; @@ -263,7 +125,9 @@ class _ConversationTabState extends State children: [ Expanded( child: Text( - userInfo?.nickName ?? '联系人', + (userInfo?.nickName ?? '').isNotEmpty + ? userInfo!.nickName! + : conversation.id, // 如果没有昵称,显示用户ID style: const TextStyle( fontSize: 16, fontWeight: FontWeight.w500, diff --git a/lib/widget/message/message_item.dart b/lib/widget/message/message_item.dart index 82d835d..e46c074 100644 --- a/lib/widget/message/message_item.dart +++ b/lib/widget/message/message_item.dart @@ -14,11 +14,13 @@ class MessageItem extends StatelessWidget { final EMMessage message; final bool isSentByMe; final EMMessage? previousMessage; + final ChatController? chatController; // 可选:直接传入的 controller const MessageItem({ required this.message, required this.isSentByMe, this.previousMessage, + this.chatController, super.key, }); @@ -51,9 +53,9 @@ class MessageItem extends StatelessWidget { showTime: shouldShowTime(), formattedTime: formatMessageTime(message.serverTime), onResend: () { - // 通过Get找到ChatController并调用重发方法 + // 通过传入的 controller 或 Get 找到 ChatController 并调用重发方法 try { - final controller = Get.find(); + final controller = chatController ?? Get.find(); controller.resendMessage(message); } catch (e) { print('重发消息失败: $e'); @@ -72,9 +74,9 @@ class MessageItem extends StatelessWidget { formattedTime: formatMessageTime(message.serverTime), message: message, onResend: () { - // 通过Get找到ChatController并调用重发方法 + // 通过传入的 controller 或 Get 找到 ChatController 并调用重发方法 try { - final controller = Get.find(); + final controller = chatController ?? Get.find(); controller.resendMessage(message); } catch (e) { print('重发消息失败: $e'); @@ -92,9 +94,9 @@ class MessageItem extends StatelessWidget { formattedTime: formatMessageTime(message.serverTime), message: message, onResend: () { - // 通过Get找到ChatController并调用重发方法 + // 通过传入的 controller 或 Get 找到 ChatController 并调用重发方法 try { - final controller = Get.find(); + final controller = chatController ?? Get.find(); controller.resendMessage(message); } catch (e) { print('重发消息失败: $e'); @@ -124,9 +126,9 @@ class MessageItem extends StatelessWidget { formattedTime: formatMessageTime(message.serverTime), message: message, onResend: () { - // 通过Get找到ChatController并调用重发方法 + // 通过传入的 controller 或 Get 找到 ChatController 并调用重发方法 try { - final controller = Get.find(); + final controller = chatController ?? Get.find(); controller.resendMessage(message); } catch (e) { print('重发消息失败: $e');