123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716 |
- 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';
- class ChatDetailPage extends StatefulWidget {
- ChatDetailPage(this.id, this.type);
- final String id;
- final String type;
- @override
- _ChatDetailPageState createState() => _ChatDetailPageState();
- // _ChatDetailPageState createState() => _ChatDetailPageState(type,index);
- }
- class _ChatDetailPageState extends State<ChatDetailPage> {
- bool hasText = false;
- // String type0;
- // String index0;
- int type = 0;
- int index = 1;
- List<dynamic> msgList = [];
- bool showEmoji = false;
- // int index = int.parse("3");
- Conversation data;
- // _ChatDetailPageState(this.type0,this.index0);
- WebSocketProvide provider = WebSocketProvide();
- ScrollController _scrollController;
- List<dynamic> userList;
- List<dynamic> storyList = [];
- List<dynamic> storyListUserOnline = [];
- //避免从附近的人打招呼重复的initRoom
- bool isTrim = false;
- 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<WebSocketProvide>(context, listen: false)
- .sendMessage(context, text, widget.id,1);
- showEmoji = false;
- // }
- // new Future.delayed(Duration(milliseconds: 1000),(){
- // setState(() {
- // hasText = false;
- // // messageList.add({'type':1,'text':text,});
- // msgList = Provider.of<WebSocketProvide>(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 = "😀,😁,😂,😃,😄,😅,😆,😉,😊,😋,😎,😍,😘,😗,😙,😚,😇,😐,😑,😶,😏,😣,😥,😮,😯,😪,😫,😴,😌,😛,😜,😝,😒,😓,😔,😕,😲,😷,😖,😞,😟,😤,😢,😭,😦,😧,😨,😬,😰,😱,😳,😵,😡,😠";
- List<String>emojiList = [];
-
- void setWebSocket() async {
- SharedPreferences prefs = await SharedPreferences.getInstance();
- // Map<String,dynamic> sessionIdObjToGet = flustars.SpUtil.getObj("sessionIdObj", (v){
- // return v;
- // });
- // LogUtil.d(sessionIdObjToGet);
- // if(sessionIdObjToGet==null){
- // print(111);
- // Map<String,dynamic> nowObj = {
- // widget.id:"hasSocket"
- // };
- // flustars.SpUtil.putObject("sessionIdObj", nowObj);
- // new Future.delayed(Duration(milliseconds: 500),(){
- // Provider.of<WebSocketProvide>(context,listen: false).incomeRoom(widget.id);
- // // getMsgList();
- // });
- // }else {
- // if(sessionIdObjToGet[widget.id]==null){
- // print(112);
- // Map<String,dynamic> thisItem = {
- // widget.id:"hasSocket"
- // };
- // sessionIdObjToGet.addAll(thisItem);
- // flustars.SpUtil.putObject("sessionIdObj", sessionIdObjToGet);
- // new Future.delayed(Duration(milliseconds: 500),(){
- // Provider.of<WebSocketProvide>(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<WebSocketProvide>(context, listen: false)
- // .incomeRoom(widget.id);
- // getStringEvent(widget.id);
- // });
- // }
- // // else if (widget.type == "nearToOne"){
- // // new Future.delayed(Duration(milliseconds: 500), () {
- // // Provider.of<WebSocketProvide>(context, listen: false)
- // // .loginAllSeconds(widget.id);
- // // getStringEvent(widget.id);
- // // });
- // else {
- // // }
- // // else if (widget.type == "oneToOne") {
- // new Future.delayed(Duration(milliseconds: 500), () {
- // Provider.of<WebSocketProvide>(context, listen: false)
- // .incomeFriend(widget.id);
- // getStringEvent(widget.id);
- // });
- // }
- // isTrim = false;
- new Future.delayed(Duration(milliseconds: 500), () {
- Provider.of<WebSocketProvide>(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<WebSocketProvide>(context, listen: false).closeWebSocket();
- });
- }
- void getMsgList() async {
- new Future.delayed(Duration(milliseconds: 2000), () {
- setState(() {
- // msgList = storyList;
- msgList = Provider.of<WebSocketProvide>(context, listen: false)
- .historyMessageqqq;
- print(JsonEncoder().convert(msgList));
- print(444443);
- _jumpBottom();
- });
- // LogUtil.d(msgList);
- // print(44444484444);
- });
- }
- @override
- void initState() {
- emojiList = emoji.split(',');
- print(emojiList);
-
- 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<dynamic> storyList = [];
- List<dynamic> storyListUserOnline = [];
- if (prefs.getStringList(roomId) != null) {
- List<String> 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<WebSocketProvide>(context).closeWebSocket();
- // Provider.of<WebSocketProvide>(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());
- });
- }
- List<String>imagesList = [];
- List<String>imagesListLast = [];
- 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<WebSocketProvide>(context, listen: false)
- .sendMessage(context, imagesUrl, widget.id,2);
- }, 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<WebSocketProvide>(
- create: (_) => provider,
- child: Scaffold(
- appBar: MyAppBar(
- centerTitle: "聊天室",
- // onPressed:(){
- // NavigatorUtils.push(context, FriendsRouter.friendsList);
- // }
- isFun: true,
- fun: () {
- // Provider.of<WebSocketProvide>(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: <Widget>[
- 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: <Widget>[
- Consumer<WebSocketProvide>(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: <Widget>[
- 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: <Widget>[
- // 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: <Widget>[
- // 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<WebSocketProvide>(context,listen: false).closeWebSocket();
- // // disposeJump();
- // super.dispose();
- // }
- }
|