message_list_subpage.dart 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366
  1. import 'dart:async';
  2. import 'dart:convert';
  3. import 'dart:math';
  4. import 'package:flutter/cupertino.dart';
  5. import 'package:flutter/material.dart';
  6. import 'package:get_it/get_it.dart';
  7. import 'package:provider/provider.dart';
  8. import 'package:sport/bean/message.dart';
  9. import 'package:sport/bean/user_info.dart';
  10. import 'package:sport/db/message_db.dart';
  11. import 'package:sport/pages/social/chat_page.dart';
  12. import 'package:sport/provider/message_model.dart';
  13. import 'package:sport/router/navigator_util.dart';
  14. import 'package:sport/services/api/inject_api.dart';
  15. import 'package:sport/services/userid.dart';
  16. import 'package:sport/utils/DateFormat.dart';
  17. import 'package:sport/utils/toast.dart';
  18. import 'package:sport/widgets/dialog/alert_dialog.dart';
  19. import 'package:sport/widgets/dialog/popupmenu.dart' as menu;
  20. import 'package:sport/widgets/error.dart';
  21. import 'package:sport/widgets/image.dart';
  22. import 'package:sport/widgets/loading.dart';
  23. class MessageListSubPage extends StatefulWidget {
  24. @override
  25. State<StatefulWidget> createState() {
  26. return _MessageListSubPageState();
  27. }
  28. }
  29. class _MessageListSubPageState extends State<MessageListSubPage> with InjectApi, UserId, AutomaticKeepAliveClientMixin {
  30. List<Map<String, dynamic>> messageList = [];
  31. StreamSubscription? _streamSubscription;
  32. bool isLoading = true;
  33. @override
  34. bool get wantKeepAlive => true;
  35. @override
  36. void initState() {
  37. super.initState();
  38. initListen();
  39. _refresh();
  40. }
  41. _refresh() {
  42. getChatIndex().then((value) {
  43. messageList = value;
  44. }).whenComplete(() => setState(() {
  45. isLoading = false;
  46. }));
  47. }
  48. // MessageInstance 类型是 服务器请求回来的类型 MessageItem 是本地 存储后的类型...
  49. Future<List<Map<String, dynamic>>> getChatIndex() async {
  50. // List<ChatMessageInstance> list = (await api.getChatIndex()).results;
  51. // var list = await MessageDB().getMessageList();
  52. messageList = [];
  53. var unReadList = await MessageDB().getMessageUnRead(selfId);
  54. // print("[unReadList]:$unReadList---------------------------------------");
  55. // print("[unReadList]:${unReadList.length}---------------------------------------");
  56. int unRead = 0;
  57. if (unReadList.length > 0) {
  58. List<int> ids = [];
  59. for (var item in unReadList) {
  60. ids.add(item['user_id']);
  61. unRead += item["cout"] as int;
  62. }
  63. List<ChatOnlineInfo> chatInfo = (await api.getChatUserInfo(json.encode(ids))).results;
  64. // 这不是是个骚的?
  65. for (int i = 0; i < unReadList.length; i++) {
  66. Map<String, dynamic> item = Map.from(unReadList[i]);
  67. // print("item $item");
  68. for (int j = 0; j < chatInfo.length; j++) {
  69. // print("chatInfo ${chatInfo[j]}");
  70. if (item['user_id'] == chatInfo[j].userId) {
  71. item['relate'] = chatInfo[j].relate;
  72. item['online'] = chatInfo[j].online;
  73. break;
  74. }
  75. }
  76. messageList.add(item);
  77. }
  78. GetIt.I<MessageModel>().notifierMessage.value = unRead;
  79. print("[unReadList]:${unRead}---------------------------------------");
  80. }
  81. return messageList;
  82. }
  83. // 在本页中如果收到了就 ...
  84. initListen() {
  85. Stream<int> queryStream = GetIt.I<MessageModel>().queryStream;
  86. _streamSubscription = queryStream.listen((count) {
  87. _refresh();
  88. });
  89. }
  90. void dispose() {
  91. super.dispose();
  92. _streamSubscription?.cancel();
  93. }
  94. Widget messageWidget(BuildContext context, Map<String, dynamic> item, int index) {
  95. int id = item['id'];
  96. String name = item['name'];
  97. String avatar = item['avatar'];
  98. bool online = item['online'];
  99. int unReadCount = item['cout'];
  100. String type = item['type'];
  101. MessageData data = MessageData.fromJson(json.decode(item['data']));
  102. GlobalKey messageKey = new GlobalKey();
  103. return GestureDetector(
  104. behavior: HitTestBehavior.opaque,
  105. key: messageKey,
  106. onTap: () async {
  107. UserInfo? info = (await api.getUserInfo("${item["user_id"]}")).data;
  108. if (info != null) await NavigatorUtil.goPage(context, (context) => ChatPage(info));
  109. int cout = item['cout'];
  110. item['cout'] = 0;
  111. setState(() {}); // 原来是为了更新那个红点的...
  112. int value = GetIt.I<MessageModel>().notifierMessage.value;
  113. GetIt.I<MessageModel>().notifierMessage.value = max(0, value - cout);
  114. },
  115. onLongPressStart: (e) async {
  116. RenderObject? renderObject = messageKey.currentContext?.findRenderObject();
  117. if (renderObject is RenderBox) {
  118. RenderBox renderBox = renderObject;
  119. var offset = renderBox.localToGlobal(Offset(0.0, renderBox.size.height));
  120. final RelativeRect position = RelativeRect.fromLTRB(
  121. e.globalPosition.dx, //取点击位置坐弹出x坐标
  122. offset.dy, //取text高度做弹出y坐标(这样弹出就不会遮挡文本)
  123. e.globalPosition.dx,
  124. offset.dy);
  125. PopupMenuEntry menuItem({String? imgUrl, String? text, dynamic callBack}) => menu.PopupMenuItem(
  126. value: callBack,
  127. child: Row(
  128. mainAxisSize: MainAxisSize.min,
  129. children: <Widget>[
  130. if (imgUrl != null)
  131. Image.asset(
  132. "lib/assets/img/$imgUrl",
  133. width: 24,
  134. ),
  135. SizedBox(
  136. width: 4,
  137. ),
  138. Text(
  139. text ?? "",
  140. )
  141. ],
  142. ),
  143. );
  144. var d = await showMenu(
  145. context: context,
  146. position: position,
  147. items: <PopupMenuEntry>[
  148. PopupMenuItem(
  149. child: Container(
  150. child: Column(
  151. children: <Widget>[menuItem(text: item['isTop'] == 1 ? "取消置顶" : "置顶", callBack: 1), menuItem(text: "删除聊天", callBack: 2)],
  152. ),
  153. ))
  154. ],
  155. );
  156. if (d == 1) {
  157. // Navigator.of(context).pop(1);
  158. await MessageDB().updateIsTop(id, item['isTop'] == 1 ? 0 : 1);
  159. } else if (d == 2) {
  160. bool flag =
  161. await showDialog(context: context, builder: (context) => CustomAlertDialog(title: '是否删除聊天记录', ok: () => Navigator.of(context).pop(true)));
  162. if (flag) {
  163. await MessageDB().deleteUserIdMessage(id);
  164. getChatIndex();
  165. ToastUtil.show("删除成功");
  166. }
  167. }
  168. }
  169. },
  170. child: Column(
  171. children: <Widget>[
  172. Padding(
  173. padding: const EdgeInsets.only(top: 12.0, bottom: 12.0),
  174. child: Row(
  175. children: <Widget>[
  176. online == true
  177. ? CircleAvatar(
  178. backgroundColor: Colors.black26,
  179. backgroundImage: userAvatarProvider(avatar),
  180. radius: 22,
  181. )
  182. : ColorFiltered(
  183. colorFilter: ColorFilter.mode(Colors.white, BlendMode.color),
  184. child: CircleAvatar(
  185. backgroundColor: Colors.black26,
  186. backgroundImage: userAvatarProvider(avatar),
  187. radius: 22,
  188. ),
  189. ),
  190. SizedBox(
  191. width: 8,
  192. ),
  193. Expanded(
  194. flex: 3,
  195. child: Column(
  196. crossAxisAlignment: CrossAxisAlignment.start,
  197. mainAxisAlignment: MainAxisAlignment.center,
  198. children: <Widget>[
  199. Row(
  200. mainAxisAlignment: MainAxisAlignment.start,
  201. children: <Widget>[
  202. Flexible(
  203. child: Text(
  204. "$name",
  205. style: Theme.of(context).textTheme.headline3!.copyWith(fontWeight: FontWeight.normal),
  206. maxLines: 1,
  207. overflow: TextOverflow.ellipsis,
  208. strutStyle: StrutStyle(forceStrutHeight: true),
  209. ),
  210. ),
  211. SizedBox(
  212. width: 4.0,
  213. ),
  214. item['relate'] != 'friends'
  215. ?
  216. // Container(
  217. // padding:
  218. // EdgeInsets.symmetric(horizontal: 5.0),
  219. // decoration: BoxDecoration(
  220. // border: Border.all(
  221. // color: Color(0xffffc400)),
  222. // borderRadius: BorderRadius.all(
  223. // Radius.circular(8.0))),
  224. // child: Text(
  225. // "未关注",
  226. // style: Theme.of(context)
  227. // .textTheme
  228. // .bodyText1
  229. // .copyWith(color: Color(0xffffc400),fontSize: 11.0),
  230. // ))
  231. Image.asset(
  232. "lib/assets/img/untrace.png",
  233. width: 44.0,
  234. height: 22.0,
  235. )
  236. : Container()
  237. ],
  238. ),
  239. SizedBox(
  240. height: 4,
  241. ),
  242. if (type == "text")
  243. Text(
  244. "${data.text}",
  245. style: Theme.of(context).textTheme.bodyText1!,
  246. maxLines: 1,
  247. overflow: TextOverflow.ellipsis,
  248. ),
  249. if (type == "forum-forward")
  250. Text(
  251. "${data.subject?.content}",
  252. style: Theme.of(context).textTheme.bodyText1!,
  253. maxLines: 1,
  254. overflow: TextOverflow.ellipsis,
  255. ),
  256. if (type == "image")
  257. Text(
  258. "分享图片",
  259. style: Theme.of(context).textTheme.bodyText1!,
  260. maxLines: 1,
  261. overflow: TextOverflow.ellipsis,
  262. ),
  263. if (type == "share")
  264. Text(
  265. "分享链接",
  266. style: Theme.of(context).textTheme.bodyText1!,
  267. maxLines: 1,
  268. overflow: TextOverflow.ellipsis,
  269. ),
  270. if (type == "game-invite")
  271. Text(
  272. "运动邀请",
  273. style: Theme.of(context).textTheme.bodyText1!,
  274. maxLines: 1,
  275. overflow: TextOverflow.ellipsis,
  276. )
  277. ],
  278. ),
  279. ),
  280. SizedBox(
  281. width: 8,
  282. ),
  283. Expanded(
  284. flex: 1,
  285. child: Column(
  286. crossAxisAlignment: CrossAxisAlignment.end,
  287. mainAxisAlignment: MainAxisAlignment.center,
  288. children: <Widget>[
  289. Text(
  290. "${DateFormat.format(DateTime.parse(item['created_at']))}",
  291. style: Theme.of(context).textTheme.bodyText1!,
  292. ),
  293. SizedBox(
  294. height: 3,
  295. ),
  296. if (unReadCount > 0)
  297. ClipOval(
  298. child: Container(
  299. width: 21.0,
  300. height: 21.0,
  301. color: Color(0xffff5B1D),
  302. child: Center(
  303. child: Text(
  304. '$unReadCount',
  305. style: TextStyle(color: Colors.white, fontSize: 12.0),
  306. ),
  307. ),
  308. ))
  309. ],
  310. ),
  311. )
  312. ],
  313. )),
  314. Divider(
  315. height: 1,
  316. )
  317. ],
  318. ),
  319. );
  320. }
  321. @override
  322. Widget build(BuildContext context) {
  323. super.build(context);
  324. if (isLoading) return RequestLoadingWidget();
  325. return messageList.length <= 0
  326. ? Center(
  327. child: RequestErrorWidget(
  328. null,
  329. msg: "暂无消息",
  330. assets: RequestErrorWidget.ASSETS_NO_COMMENT,
  331. ),
  332. )
  333. : ListView.builder(
  334. padding: EdgeInsets.symmetric(horizontal: 12.0),
  335. // separatorBuilder: (context, index) => Divider(
  336. // height: 1,
  337. // ),
  338. itemCount: messageList.length,
  339. itemBuilder: (context, index) {
  340. Map<String, dynamic> item = messageList[index];
  341. return messageWidget(context, item, index);
  342. });
  343. }
  344. }