import 'package:flutter/material.dart'; import 'package:liftmanager/widgets/app_bar.dart'; import '../provide/websocket.dart'; import 'package:flutter_screenutil/flutter_screenutil.dart'; import '../common/style/style.dart'; import './chat_detail/chat_content_view.dart'; import '../model/conversation.dart'; import 'package:provider/provider.dart'; import 'package:liftmanager/widgets/load_image.dart'; import 'package:liftmanager/internal/bbs/model/talk_model.dart'; import 'package:liftmanager/utils/url.dart'; import 'package:liftmanager/utils/log_util.dart'; import 'dart:convert'; import 'package:dart_notification_center/dart_notification_center.dart'; import 'package:liftmanager/utils/fast_notification.dart'; import 'package:liftmanager/routers/fluro_navigator.dart'; import 'package:liftmanager/internal/friends/friends_router.dart'; import 'package:liftmanager/routers/routers.dart'; import 'package:liftmanager/common/common.dart'; import 'package:flustars/flustars.dart' as flustars; import 'package:shared_preferences/shared_preferences.dart'; import 'package:liftmanager/utils/toast.dart'; import 'package:image_picker/image_picker.dart'; import 'package:liftmanager/net/api_service.dart'; import 'package:liftmanager/utils/theme_utils.dart'; import 'package:liftmanager/widgets/chat_list_view.dart'; class ChatDetailPage extends StatefulWidget { ChatDetailPage(this.id, this.type,this.toUserId); final String id; final String type; final String toUserId; @override _ChatDetailPageState createState() => _ChatDetailPageState(); // _ChatDetailPageState createState() => _ChatDetailPageState(type,index); } class _ChatDetailPageState extends State { bool hasText = false; // String type0; // String index0; int type = 0; int index = 1; List msgList = []; bool showEmoji = false; // int index = int.parse("3"); Conversation data; // _ChatDetailPageState(this.type0,this.index0); WebSocketProvide provider = WebSocketProvide(); ScrollController _scrollController; List userList; List storyList = []; List storyListUserOnline = []; //避免从附近的人打招呼重复的initRoom bool isTrim = false; int dataTable; final controller = TextEditingController(); void _handleSubmitted(context, String text) { FocusScope.of(context).requestFocus(FocusNode()); if (controller.text.length > 0) { FocusScope.of(context).requestFocus(FocusNode()); print('发送${text}'); print(type); // if(type == 1){ print(666); Provider.of(context, listen: false) .sendMessage(context, text, widget.id,1,dataTable,widget.toUserId); showEmoji = false; // } // new Future.delayed(Duration(milliseconds: 1000),(){ // setState(() { // hasText = false; // // messageList.add({'type':1,'text':text,}); // msgList = Provider.of(context,listen: false).historyMessageqqq; // }); // }); controller.clear(); //清空输入框 FocusScope.of(context).requestFocus(FocusNode()); _jumpBottom(); } else { toasts("请输入"); } } void _jumpBottom() { //滚动到底部 _scrollController.animateTo(9999999999, curve: Curves.easeOut, duration: Duration(milliseconds: 200)); } String emoji = "😀,😁,😂,😃,😄,😅,😆,😉,😊,😋,😎,😍,😘,😗,😙,😚,😇,😐,😑,😶,😏,😣,😥,😮,😯,😪,😫,😴,😌,😛,😜,😝,😒,😓,😔,😕,😲,😷,😖,😞,😟,😤,😢,😭,😦,😧,😨,😬,😰,😱,😳,😵,😡,😠"; ListemojiList = []; void setWebSocket() async { SharedPreferences prefs = await SharedPreferences.getInstance(); // Map sessionIdObjToGet = flustars.SpUtil.getObj("sessionIdObj", (v){ // return v; // }); // LogUtil.d(sessionIdObjToGet); // if(sessionIdObjToGet==null){ // print(111); // Map nowObj = { // widget.id:"hasSocket" // }; // flustars.SpUtil.putObject("sessionIdObj", nowObj); // new Future.delayed(Duration(milliseconds: 500),(){ // Provider.of(context,listen: false).incomeRoom(widget.id); // // getMsgList(); // }); // }else { // if(sessionIdObjToGet[widget.id]==null){ // print(112); // Map thisItem = { // widget.id:"hasSocket" // }; // sessionIdObjToGet.addAll(thisItem); // flustars.SpUtil.putObject("sessionIdObj", sessionIdObjToGet); // new Future.delayed(Duration(milliseconds: 500),(){ // Provider.of(context,listen: false).incomeRoom(widget.id); // // getMsgList(); // }); // } // } // if ((widget.type == "someToOne")&& isTrim==false) { // if ((widget.type == "someToOne" || widget.type == "nearToOne")&& isTrim==false) { // new Future.delayed(Duration(milliseconds: 500), () { // Provider.of(context, listen: false) // .incomeRoom(widget.id); // getStringEvent(widget.id); // }); // } // // else if (widget.type == "nearToOne"){ // // new Future.delayed(Duration(milliseconds: 500), () { // // Provider.of(context, listen: false) // // .loginAllSeconds(widget.id); // // getStringEvent(widget.id); // // }); // else { // // } // // else if (widget.type == "oneToOne") { // new Future.delayed(Duration(milliseconds: 500), () { // Provider.of(context, listen: false) // .incomeFriend(widget.id); // getStringEvent(widget.id); // }); // } // isTrim = false; new Future.delayed(Duration(milliseconds: 500), () { Provider.of(context, listen: false) .incomeRoom(widget.id); getStringEvent(widget.id); }); } void initJump() async { new Future.delayed(Duration(milliseconds: 500), () { FocusScope.of(context).requestFocus(FocusNode()); _jumpBottom(); }); } void disposeJump() async { new Future.delayed(Duration(milliseconds: 500), () { Provider.of(context, listen: false).closeWebSocket(); }); } void getMsgList() async { new Future.delayed(Duration(milliseconds: 2000), () { setState(() { // msgList = storyList; msgList = Provider.of(context, listen: false) .historyMessageqqq; print(JsonEncoder().convert(msgList)); print(444443); _jumpBottom(); }); // LogUtil.d(msgList); // print(44444484444); }); } @override void initState() { emojiList = emoji.split(','); // print(emojiList); if(widget.type == "nearToOne"){ dataTable = 3; }else { dataTable = null; } print(JsonEncoder().convert(emojiList)); print(66669999); // DartNotificationCenter.registerChannel(channel: 'socket_event'); // DartNotificationCenter.post( // channel: "socket_event", // options: 'with options!!', // ); FastNotification.addListener("chat_room", (historyMessageqqq) { if (mounted) { setState(() { msgList = historyMessageqqq; print(JsonEncoder().convert(msgList)); print(4444499); }); _jumpBottom(); } }); FastNotification.addListener("set_user", (setUserList) { if (mounted) { new Future.delayed(Duration(milliseconds: 1000), () { setState(() { userList = setUserList; }); }); } }); FastNotification.addListener("initSocket", (initThisSocket) { if (mounted) { isTrim = true; setWebSocket(); _jumpBottom(); FocusScope.of(context).requestFocus(FocusNode()); toasts("聊天室已重连!"); } }); print("开启123"); super.initState(); _scrollController = new ScrollController(); setWebSocket(); // getStringEvent(widget.id); initJump(); } @override void didChangeDependencies() { super.didChangeDependencies(); } void getStringEvent(roomId) async { SharedPreferences prefs = await SharedPreferences.getInstance(); List storyList = []; List storyListUserOnline = []; if (prefs.getStringList(roomId) != null) { List hisString = prefs.getStringList(roomId); storyList = hisString.map((item) => jsonDecode(item)).toList(); // new Future.delayed(Duration(milliseconds: 1000),(){ // setState(() { // msgList = storyList; // userList = storyListUserOnline; // print(JsonEncoder().convert(msgList)); // print(444447); // _jumpBottom(); // }); // // LogUtil.d(msgList); // // print(44444484444); // }); } else { prefs.setStringList(roomId, []); } // if (flustars.SpUtil.getString(roomId + "userOnline") != null && // flustars.SpUtil.getString(roomId + "userOnline") != "") { // // if(prefs.getString(roomId+"userOnline")!=null){ // // String hisStringUserOnline = prefs.getString(roomId+"userOnline"); // // flustars.SpUtil.putString(roomId+"userOnline", res.token); // String hisStringUserOnline = // flustars.SpUtil.getString(roomId + "userOnline"); // for (var value in JsonDecoder().convert(hisStringUserOnline)) { // print(value); // storyListUserOnline.add(value); // } // ; // // storyListUserOnline = JsonDecoder().convert(hisStringUserOnline); // // storyListUserOnline = hisStringUserOnline.map((item)=>jsonDecode(item)).toList(); // } else { // // prefs.setString(roomId+"userOnline",''); // } // print(JsonEncoder().convert(storyList)); // print(JsonEncoder().convert(storyListUserOnline)); new Future.delayed(Duration(milliseconds: 1000), () { setState(() { if (storyList.length > 0) { msgList = storyList; } if (storyListUserOnline.length > 0) { userList = storyListUserOnline; } print(JsonEncoder().convert(msgList)); print(444447); _jumpBottom(); }); // LogUtil.d(msgList); // print(44444484444); }); } // @override // void didChangeDependencies() { // // Provider.of(context).closeWebSocket(); // Provider.of(context,listen: false).closeWebSocket(); // super.didChangeDependencies(); // } FocusNode blankNode = FocusNode(); ///选择图片 void selectPicker() { showDialog( context: context, builder: (BuildContext context) { return SimpleDialog( title: Text("选择方式"), children: ["拍照", '从手机相册选择'].map((String value) { print("$value"); return SimpleDialogOption( child: Text( "${value}", style: TextStyle(fontSize: 16, fontWeight: FontWeight.w500), ), onPressed: () { _getImage(value == '拍照' ? 1 : 0); Navigator.of(context).pop(); }, ); }).toList()); }); } ListimagesList = []; ListimagesListLast = []; void _getImage(int key) async { try { var _imageFile = await ImagePicker.pickImage( source: key == 1 ? ImageSource.camera : ImageSource.gallery, maxWidth: 800, imageQuality: 95); print(_imageFile); print(3333); if (_imageFile != null) { // images.add(_imageFile); upLoadFileOnce(_imageFile.path); // setState(() {}); } } catch (e) { toasts("没有权限,无法打开相册!"); } } upLoadFileOnce(path) { showLoading(context, "正在发送..."); NewApiService().upload(path, onSuccess: (res) { // imagesUrl.add(res.path); dismissLoading(context); String imagesUrl; imagesUrl = (res.pathUrl); Provider.of(context, listen: false) .sendMessage(context, imagesUrl, widget.id,2,dataTable,widget.toUserId); }, onError: (code, msg) { dismissLoading(context); toasts(msg); }); } @override Widget build(BuildContext context) { double width = MediaQuery.of(context).size.width; // print(JsonEncoder().convert(msgList)); imagesList = []; msgList.forEach((element) { if(element["type"]==2){ imagesList.add(element["msg"]); } }); // print(1234567980); return ChangeNotifierProvider( create: (_) => provider, child: Scaffold( appBar: MyAppBar( centerTitle: "聊天室", // onPressed:(){ // NavigatorUtils.push(context, FriendsRouter.friendsList); // } isFun: true, fun: () { // Provider.of(context,listen: false).closeWebSocket(); // NavigatorUtils.push(context, FriendsRouter.friendsList); Navigator.popUntil(context, ModalRoute.withName('/home')); // NavigatorUtils.push(context, FriendsRouter.friendsList, clearStack: true); // NavigatorUtils.push(context, Routers.home, clearStack: true); }, ), body: GestureDetector( onTap: () { // 点击空白页面关闭键盘 FocusScope.of(context).requestFocus(blankNode); }, child: Stack( children: [ GestureDetector( onTap: (){ setState(() { showEmoji = false; }); }, child: Container( padding: widget.type == "someToOne" ? EdgeInsets.only(top: ScreenUtil().setWidth(10)) : EdgeInsets.only(top: ScreenUtil().setWidth(10)), // color: Colors.red, color: ThemeUtils.getTabsBg(context), child: Column( children: [ Consumer(builder: (context, child, val) { return Expanded( child: ListView.builder( controller: _scrollController, physics: ClampingScrollPhysics(), itemBuilder: (BuildContext context, int index) { int typeUser; // print(msgList[index]["fromUser"]); // print(msgList[index]["msg"]); // print(jsonDecode(msgList[index])["fromUser"]); // print(1234567890); if (msgList[index]["fromUser"] == flustars.SpUtil.getString(Constant.userId)) { typeUser = 1; } else { typeUser = 0; } // if(msgList[index]["type"]==2){ // imagesList.add(msgList[index]["msg"]); // print(msgList[index]["msg"]); // } // print("///////////////////////////////////////////"); // LogUtil.d(imagesList); // print("///////////////////////////////////////////"); return ChatContentView( contentIndex:index, urlList:imagesList, type: typeUser, text: msgList[index]["msg"], msgType: msgList[index]["type"], avatar: msgList[index]["avatarUrl"], username: msgList[index]["name"], isNetwork: msgList[index]["avatarUrl"] != null ? true : false); // return ChatContentView(type:typeUser,text:msgList[index]["msg"],avatar:imgFontUrl+msgList[index]["avatarUrl"],username:msgList[index]["name"],isNetwork:msgList[index]["avatarUrl"]!=null?true:false); }, itemCount: msgList.length, // itemCount:type == 1 ? list.length : messageList.length , )); }), showEmoji?Container( padding: EdgeInsets.only(left:ScreenUtil().setWidth(6),top:ScreenUtil().setWidth(10),bottom:ScreenUtil().setWidth(10),right: ScreenUtil().setWidth(6)), color: Colors.white, height: ScreenUtil().setWidth(200), child: GridView.extent( //横轴的最大长度 maxCrossAxisExtent: 35, //内边距 padding: EdgeInsets.all(4.0), //垂直方向的间距 mainAxisSpacing: 4.0, //水平方向的间距 crossAxisSpacing: 4.0, children: emojiList.map((element) { return GestureDetector( onTap: (){ controller.text += element; }, child: Text( element, style: TextStyle( color: Color(0xff000000), fontSize: ScreenUtil().setSp(22)), textAlign: TextAlign.center, ), ); }).toList(), ) ):Container(child: null,), Container( padding: EdgeInsets.only( top: ScreenUtil().setHeight(2.0), bottom: ScreenUtil().setHeight(2.0), left: 0, right: 0), color: ThemeUtils.getDialogTextFieldColor(context), child: Row( children: [ Container( width: ScreenUtil().setWidth(30.0), margin: EdgeInsets.only( right: ScreenUtil().setWidth(10.0)), child: IconButton( icon: Icon(ICons.ADD), onPressed: () { selectPicker(); FocusScope.of(context).requestFocus(FocusNode()); }), ), Expanded( child: Container( // padding: EdgeInsets.only(top: ScreenUtil().setHeight(8.0), bottom: ScreenUtil().setHeight(8.0)), height: ScreenUtil().setHeight(30.0), decoration: BoxDecoration( borderRadius: BorderRadius.all(Radius.circular(5.0)), color: Colors.white), child: TextField( controller: controller, // decoration: InputDecoration.collapsed(hintText: null), decoration: InputDecoration( border: InputBorder.none, ), maxLines: 1, autocorrect: true, autofocus: false, textAlign: TextAlign.start, style: TextStyle(color: Colors.black), cursorColor: Colors.green, onChanged: (text) { setState(() { hasText = text.length > 0 ? true : false; }); // print('change=================== $text'); }, // onSubmitted:_handleSubmitted, enabled: true, //bu禁用 ), )), Container( width: ScreenUtil().setWidth(30.0), child: IconButton( icon: Icon(ICons.FACES), //发送按钮图标 onPressed: () { print('打开表情面板'); setState(() { showEmoji = !showEmoji; }); }), ), Container( width: ScreenUtil().setWidth(30.0), margin: EdgeInsets.only( right: ScreenUtil().setWidth(10.0)), child: IconButton( //发送按钮或者+按钮 icon: Icon(Icons.send), onPressed: () { if (controller.text == null || controller.text == '') { toasts("请输入内容"); } else { _handleSubmitted(context, controller.text); } }), ) ], ), ) ], ), ), ), // widget.type == "someToOne" // ? Positioned( // top: 0, // left: 0, // child: userList != null && userList != [] // ? Container( // width: width, // height: ScreenUtil().setWidth(100), // padding: EdgeInsets.only( // top: ScreenUtil().setWidth(15), // bottom: ScreenUtil().setWidth(10)), // color: Colors.white, // child: ListView( // scrollDirection: Axis.horizontal, // children: userList.asMap().keys.map((i) { // if (i == 0) { // return userList[i]["flag"] // ? Container( // padding: EdgeInsets.only( // right: // ScreenUtil().setWidth(15), // left: ScreenUtil() // .setWidth(15)), // child: Column(children: [ // ClipRRect( // borderRadius: // BorderRadius.all( // Radius.circular( // 22)), // child: LoadNetworkImage( // userList[i]["avatarUrl"], // width: ScreenUtil() // .setWidth(43), // height: ScreenUtil() // .setWidth(43), // ) // // userList[i]["avatarUrl"]!=null&&userList[i]["avatarUrl"]!=null ? // // FadeInImage.assetNetwork( // // placeholder: 'assets/images/temporary/avator2.png', // // //预览图 // // fit: BoxFit.fitWidth, // // image: imgFontUrl+userList[i]["avatarUrl"], // // width: ScreenUtil().setWidth(43), // // height:ScreenUtil().setWidth(43), // // ) // // :Image.asset( // // 'assets/images/temporary/avator2.png', // // fit: BoxFit.cover, // // width: ScreenUtil().setWidth(43), // // height:ScreenUtil().setWidth(43), // // ), // ), // Container( // height: 5, child: null), // Text( // userList[i]["name"], // style: TextStyle( // color: Color(0xff000000), // fontSize: ScreenUtil() // .setSp(14)), // textAlign: TextAlign.start, // ), // ]), // ) // : Container(child: null); // } else { // return userList[i]["flag"] // ? Container( // padding: EdgeInsets.only( // right: ScreenUtil() // .setWidth(15)), // child: Column(children: [ // ClipRRect( // borderRadius: // BorderRadius.all( // Radius.circular(22)), // child: LoadNetworkImage( // userList[i]["avatarUrl"], // width: ScreenUtil() // .setWidth(43), // height: ScreenUtil() // .setWidth(43), // ), // // userList[i]["avatarUrl"]!=null&&userList[i]["avatarUrl"]!=null ? // // FadeInImage.assetNetwork( // // placeholder: 'assets/images/temporary/avator2.png', // // //预览图 // // fit: BoxFit.fitWidth, // // image: imgFontUrl+userList[i]["avatarUrl"], // // width: ScreenUtil().setWidth(43), // // height:ScreenUtil().setWidth(43), // // ) // // :Image.asset( // // 'assets/images/temporary/avator2.png', // // fit: BoxFit.cover, // // width: ScreenUtil().setWidth(43), // // height:ScreenUtil().setWidth(43), // // ), // ), // Container( // height: 5, child: null), // Text( // userList[i]["name"], // style: TextStyle( // color: Color(0xff000000), // fontSize: ScreenUtil() // .setSp(14)), // textAlign: TextAlign.start, // ), // ]), // ) // : Container(child: null); // } // }).toList())) // : Container( // child: null, // )) // : Container(child: null) ], ), ), ), ); } // @override // void dispose() { // Provider.of(context,listen: false).closeWebSocket(); // // disposeJump(); // super.dispose(); // } }