123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366 |
- import 'dart:async';
- import 'dart:convert';
- import 'dart:math';
- import 'package:flutter/cupertino.dart';
- import 'package:flutter/material.dart';
- import 'package:get_it/get_it.dart';
- import 'package:provider/provider.dart';
- import 'package:sport/bean/message.dart';
- import 'package:sport/bean/user_info.dart';
- import 'package:sport/db/message_db.dart';
- import 'package:sport/pages/social/chat_page.dart';
- import 'package:sport/provider/message_model.dart';
- import 'package:sport/router/navigator_util.dart';
- import 'package:sport/services/api/inject_api.dart';
- import 'package:sport/services/userid.dart';
- import 'package:sport/utils/DateFormat.dart';
- import 'package:sport/utils/toast.dart';
- import 'package:sport/widgets/dialog/alert_dialog.dart';
- import 'package:sport/widgets/dialog/popupmenu.dart' as menu;
- import 'package:sport/widgets/error.dart';
- import 'package:sport/widgets/image.dart';
- import 'package:sport/widgets/loading.dart';
- class MessageListSubPage extends StatefulWidget {
- @override
- State<StatefulWidget> createState() {
- return _MessageListSubPageState();
- }
- }
- class _MessageListSubPageState extends State<MessageListSubPage> with InjectApi, UserId, AutomaticKeepAliveClientMixin {
- List<Map<String, dynamic>> messageList = [];
- StreamSubscription? _streamSubscription;
- bool isLoading = true;
- @override
- bool get wantKeepAlive => true;
- @override
- void initState() {
- super.initState();
- initListen();
- _refresh();
- }
- _refresh() {
- getChatIndex().then((value) {
- messageList = value;
- }).whenComplete(() => setState(() {
- isLoading = false;
- }));
- }
- // MessageInstance 类型是 服务器请求回来的类型 MessageItem 是本地 存储后的类型...
- Future<List<Map<String, dynamic>>> getChatIndex() async {
- // List<ChatMessageInstance> list = (await api.getChatIndex()).results;
- // var list = await MessageDB().getMessageList();
- messageList = [];
- var unReadList = await MessageDB().getMessageUnRead(selfId);
- // print("[unReadList]:$unReadList---------------------------------------");
- // print("[unReadList]:${unReadList.length}---------------------------------------");
- int unRead = 0;
- if (unReadList.length > 0) {
- List<int> ids = [];
- for (var item in unReadList) {
- ids.add(item['user_id']);
- unRead += item["cout"] as int;
- }
- List<ChatOnlineInfo> chatInfo = (await api.getChatUserInfo(json.encode(ids))).results;
- // 这不是是个骚的?
- for (int i = 0; i < unReadList.length; i++) {
- Map<String, dynamic> item = Map.from(unReadList[i]);
- // print("item $item");
- for (int j = 0; j < chatInfo.length; j++) {
- // print("chatInfo ${chatInfo[j]}");
- if (item['user_id'] == chatInfo[j].userId) {
- item['relate'] = chatInfo[j].relate;
- item['online'] = chatInfo[j].online;
- break;
- }
- }
- messageList.add(item);
- }
- GetIt.I<MessageModel>().notifierMessage.value = unRead;
- print("[unReadList]:${unRead}---------------------------------------");
- }
- return messageList;
- }
- // 在本页中如果收到了就 ...
- initListen() {
- Stream<int> queryStream = GetIt.I<MessageModel>().queryStream;
- _streamSubscription = queryStream.listen((count) {
- _refresh();
- });
- }
- void dispose() {
- super.dispose();
- _streamSubscription?.cancel();
- }
- Widget messageWidget(BuildContext context, Map<String, dynamic> item, int index) {
- int id = item['id'];
- String name = item['name'];
- String avatar = item['avatar'];
- bool online = item['online'];
- int unReadCount = item['cout'];
- String type = item['type'];
- MessageData data = MessageData.fromJson(json.decode(item['data']));
- GlobalKey messageKey = new GlobalKey();
- return GestureDetector(
- behavior: HitTestBehavior.opaque,
- key: messageKey,
- onTap: () async {
- UserInfo? info = (await api.getUserInfo("${item["user_id"]}")).data;
- if (info != null) await NavigatorUtil.goPage(context, (context) => ChatPage(info));
- int cout = item['cout'];
- item['cout'] = 0;
- setState(() {}); // 原来是为了更新那个红点的...
- int value = GetIt.I<MessageModel>().notifierMessage.value;
- GetIt.I<MessageModel>().notifierMessage.value = max(0, value - cout);
- },
- onLongPressStart: (e) async {
- RenderObject? renderObject = messageKey.currentContext?.findRenderObject();
- if (renderObject is RenderBox) {
- RenderBox renderBox = renderObject;
- var offset = renderBox.localToGlobal(Offset(0.0, renderBox.size.height));
- final RelativeRect position = RelativeRect.fromLTRB(
- e.globalPosition.dx, //取点击位置坐弹出x坐标
- offset.dy, //取text高度做弹出y坐标(这样弹出就不会遮挡文本)
- e.globalPosition.dx,
- offset.dy);
- PopupMenuEntry menuItem({String? imgUrl, String? text, dynamic callBack}) => menu.PopupMenuItem(
- value: callBack,
- child: Row(
- mainAxisSize: MainAxisSize.min,
- children: <Widget>[
- if (imgUrl != null)
- Image.asset(
- "lib/assets/img/$imgUrl",
- width: 24,
- ),
- SizedBox(
- width: 4,
- ),
- Text(
- text ?? "",
- )
- ],
- ),
- );
- var d = await showMenu(
- context: context,
- position: position,
- items: <PopupMenuEntry>[
- PopupMenuItem(
- child: Container(
- child: Column(
- children: <Widget>[menuItem(text: item['isTop'] == 1 ? "取消置顶" : "置顶", callBack: 1), menuItem(text: "删除聊天", callBack: 2)],
- ),
- ))
- ],
- );
- if (d == 1) {
- // Navigator.of(context).pop(1);
- await MessageDB().updateIsTop(id, item['isTop'] == 1 ? 0 : 1);
- } else if (d == 2) {
- bool flag =
- await showDialog(context: context, builder: (context) => CustomAlertDialog(title: '是否删除聊天记录', ok: () => Navigator.of(context).pop(true)));
- if (flag) {
- await MessageDB().deleteUserIdMessage(id);
- getChatIndex();
- ToastUtil.show("删除成功");
- }
- }
- }
- },
- child: Column(
- children: <Widget>[
- Padding(
- padding: const EdgeInsets.only(top: 12.0, bottom: 12.0),
- child: Row(
- children: <Widget>[
- online == true
- ? CircleAvatar(
- backgroundColor: Colors.black26,
- backgroundImage: userAvatarProvider(avatar),
- radius: 22,
- )
- : ColorFiltered(
- colorFilter: ColorFilter.mode(Colors.white, BlendMode.color),
- child: CircleAvatar(
- backgroundColor: Colors.black26,
- backgroundImage: userAvatarProvider(avatar),
- radius: 22,
- ),
- ),
- SizedBox(
- width: 8,
- ),
- Expanded(
- flex: 3,
- child: Column(
- crossAxisAlignment: CrossAxisAlignment.start,
- mainAxisAlignment: MainAxisAlignment.center,
- children: <Widget>[
- Row(
- mainAxisAlignment: MainAxisAlignment.start,
- children: <Widget>[
- Flexible(
- child: Text(
- "$name",
- style: Theme.of(context).textTheme.headline3!.copyWith(fontWeight: FontWeight.normal),
- maxLines: 1,
- overflow: TextOverflow.ellipsis,
- strutStyle: StrutStyle(forceStrutHeight: true),
- ),
- ),
- SizedBox(
- width: 4.0,
- ),
- item['relate'] != 'friends'
- ?
- // Container(
- // padding:
- // EdgeInsets.symmetric(horizontal: 5.0),
- // decoration: BoxDecoration(
- // border: Border.all(
- // color: Color(0xffffc400)),
- // borderRadius: BorderRadius.all(
- // Radius.circular(8.0))),
- // child: Text(
- // "未关注",
- // style: Theme.of(context)
- // .textTheme
- // .bodyText1
- // .copyWith(color: Color(0xffffc400),fontSize: 11.0),
- // ))
- Image.asset(
- "lib/assets/img/untrace.png",
- width: 44.0,
- height: 22.0,
- )
- : Container()
- ],
- ),
- SizedBox(
- height: 4,
- ),
- if (type == "text")
- Text(
- "${data.text}",
- style: Theme.of(context).textTheme.bodyText1!,
- maxLines: 1,
- overflow: TextOverflow.ellipsis,
- ),
- if (type == "forum-forward")
- Text(
- "${data.subject?.content}",
- style: Theme.of(context).textTheme.bodyText1!,
- maxLines: 1,
- overflow: TextOverflow.ellipsis,
- ),
- if (type == "image")
- Text(
- "分享图片",
- style: Theme.of(context).textTheme.bodyText1!,
- maxLines: 1,
- overflow: TextOverflow.ellipsis,
- ),
- if (type == "share")
- Text(
- "分享链接",
- style: Theme.of(context).textTheme.bodyText1!,
- maxLines: 1,
- overflow: TextOverflow.ellipsis,
- ),
- if (type == "game-invite")
- Text(
- "运动邀请",
- style: Theme.of(context).textTheme.bodyText1!,
- maxLines: 1,
- overflow: TextOverflow.ellipsis,
- )
- ],
- ),
- ),
- SizedBox(
- width: 8,
- ),
- Expanded(
- flex: 1,
- child: Column(
- crossAxisAlignment: CrossAxisAlignment.end,
- mainAxisAlignment: MainAxisAlignment.center,
- children: <Widget>[
- Text(
- "${DateFormat.format(DateTime.parse(item['created_at']))}",
- style: Theme.of(context).textTheme.bodyText1!,
- ),
- SizedBox(
- height: 3,
- ),
- if (unReadCount > 0)
- ClipOval(
- child: Container(
- width: 21.0,
- height: 21.0,
- color: Color(0xffff5B1D),
- child: Center(
- child: Text(
- '$unReadCount',
- style: TextStyle(color: Colors.white, fontSize: 12.0),
- ),
- ),
- ))
- ],
- ),
- )
- ],
- )),
- Divider(
- height: 1,
- )
- ],
- ),
- );
- }
- @override
- Widget build(BuildContext context) {
- super.build(context);
- if (isLoading) return RequestLoadingWidget();
- return messageList.length <= 0
- ? Center(
- child: RequestErrorWidget(
- null,
- msg: "暂无消息",
- assets: RequestErrorWidget.ASSETS_NO_COMMENT,
- ),
- )
- : ListView.builder(
- padding: EdgeInsets.symmetric(horizontal: 12.0),
- // separatorBuilder: (context, index) => Divider(
- // height: 1,
- // ),
- itemCount: messageList.length,
- itemBuilder: (context, index) {
- Map<String, dynamic> item = messageList[index];
- return messageWidget(context, item, index);
- });
- }
- }
|