You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 
 
 

1403 lines
47 KiB

import 'dart:async';
import 'dart:convert';
import 'dart:io';
import 'dart:ui';
import 'package:dio/dio.dart';
import 'package:emoji_picker_flutter/emoji_picker_flutter.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:flutter_smart_dialog/flutter_smart_dialog.dart';
import 'package:huixiang/im/database/message.dart';
import 'package:huixiang/im/out/message.pb.dart';
import 'package:huixiang/main.dart';
import 'package:huixiang/retrofit/data/im_user.dart';
import 'package:huixiang/retrofit/retrofit_api.dart';
import 'package:huixiang/view_widget/classic_header.dart';
import 'package:huixiang/view_widget/my_appbar.dart';
import 'package:image_gallery_saver/image_gallery_saver.dart';
import 'package:image_pickers/image_pickers.dart';
import 'package:permission_handler/permission_handler.dart';
import 'package:pull_to_refresh/pull_to_refresh.dart';
import 'package:shared_preferences/shared_preferences.dart';
import '../../community/release_dynamic.dart';
import '../../generated/l10n.dart';
import '../../utils/font_weight.dart';
import '../retrofit/data/base_data.dart';
import '../retrofit/data/user_info.dart';
import '../utils/flutter_utils.dart';
import '../view_widget/custom_image.dart';
import '../view_widget/request_permission.dart';
import 'im_view/on_chat_message.dart';
import 'im_view/on_chat_msg_instance.dart';
class ChatDetailsPage extends StatefulWidget {
final Map<String, dynamic> arguments;
ChatDetailsPage({this.arguments});
@override
State<StatefulWidget> createState() {
return _ChatDetailsPage();
}
}
class _ChatDetailsPage extends State<ChatDetailsPage>
with WidgetsBindingObserver
implements OnChatMessage {
ApiService apiService;
List<Medias> mediaPaths = [];
int selectCount = 9;
int dynamicType = 0;
final TextEditingController chatController = TextEditingController();
bool emojiShowing = false;
double keyboard = -1;
bool needShowSmiley = false;
bool needHideSmiley = false;
bool isKeyBoardShow = false;
bool moreShow = false;
bool needShowMore = false;
bool needHideMore = false;
var commentFocus = FocusNode();
String hintText = "输入消息内容...";
UserInfo userInfo;
final OnChatMessage _tempOnChatMessage =
OnChatMsgInstance.instance.onChatMessage;
final ScrollController scrollController = ScrollController();
String tex = "";
String selfUserId = "";
ImUser _toUser;
String conversation;
List<String> imageUrl = [];
@override
void onMessage(txt) {
// SmartDialog.showToast("聊天 $txt", alignment: Alignment.center);
}
RefreshController refreshController = RefreshController();
List<Message> messages = [];
int page = 0;
loadMessageList() async {
selfUserId = (await SharedPreferences.getInstance()).getString("userId");
conversation = conversationId(selfUserId, _toUser.mid);
ImUser imUser = await hxDatabase.queryImUserById(conversation);
if (imUser == null) {
await hxDatabase.insertOrUpdateImUser(_toUser.toJson());
}
// unread msg 2 read state
await hxDatabase.readMessage(conversation);
await refresh();
socketClient.addCallback(_toUser.mid, (Message message) {
messages.insert(0, message);
if (message.msgType == MsgType.VIDEO.value || message.msgType == MsgType.IMAGE.value) {
imageUrl.add(message.attach);
}
messageShowTime().then((value) {
refreshState();
jumpToBottom();
});
});
messageImageUrl();
refreshState();
jumpToBottom();
}
Future refresh() async {
List<Message> messagePage = await hxDatabase.queryUList(conversation, page: page + 1, pageSize: 10);
debugPrint("refresh-message-list: ${messagePage.length} page: $page");
if (messagePage.isEmpty) {
refreshController.loadNoData();
return;
} else {
refreshController.loadComplete();
page += 1;
}
if (page == 1) {
messages = messagePage;
} else {
messages.addAll(messagePage);
}
await messageShowTime();
return Future.value();
}
/// 消息中的图片
messageImageUrl() {
imageUrl = messages.where((e) => e.msgType == MsgType.VIDEO.value || e.msgType == MsgType.IMAGE.value).map((e) => e.attach).toList();
}
Future messageShowTime() async {
List<Message> messagePages = await hxDatabase.queryTList(conversation);
for (var value in messages) {
Message message = messagePages
.firstWhere((element) => value.id == element.id, orElse: () => null);
value.showTime = message != null;
}
}
SharedPreferences sharedPre;
///查询个人信息
queryUser() async {
sharedPre = await SharedPreferences.getInstance();
if (apiService == null)
apiService = ApiService(Dio(),
context: context, token: sharedPre.getString("token"));
if (sharedPre.containsKey('user') &&
sharedPre.getString('user') != null &&
sharedPre.getString('user') != "") {
userInfo = UserInfo.fromJson(jsonDecode(sharedPre.getString('user')));
if (userInfo.phone?.isNotEmpty ?? false) {
setState(() {});
return;
}
}
BaseData<UserInfo> baseData =
await apiService.queryInfo().catchError((onError) {});
if (baseData != null && baseData.isSuccess) {
setState(() {
userInfo = baseData.data;
});
SharedPreferences.getInstance().then((value) => {
value.setString('user', jsonEncode(baseData.data)),
});
}
}
refreshState() {
if (mounted) setState(() {});
}
@override
void initState() {
super.initState();
_toUser = widget.arguments["toUser"];
OnChatMsgInstance.instance.onChatMessage = this;
WidgetsBinding.instance.addObserver(this);
commentFocus.addListener(_focusNodeListener);
queryUser();
loadMessageList();
}
void jumpToBottom() {
Future.delayed(const Duration(milliseconds: 100), () {
scrollController.position.jumpTo(0);
});
}
void didChangeMetrics() {
WidgetsBinding.instance.addPostFrameCallback((_) {
if (!mounted) return;
isKeyBoardShow = MediaQuery.of(context).viewInsets.bottom > 0;
if (MediaQuery.of(context).viewInsets.bottom == 0) {
if (isKeyBoardShow) {
FocusScope.of(context).requestFocus(FocusNode());
if (mounted) if (!emojiShowing) if (!moreShow)
setState(() {
hintText = "请输入消息内容...";
isKeyBoardShow = false;
});
}
} else {
if (mounted)
setState(() {
isKeyBoardShow = true;
});
}
});
if (needShowSmiley && window.viewInsets.bottom <= 0.1) {
needShowSmiley = false;
setState(() {
emojiShowing = true;
});
}
if (needHideSmiley && window.viewInsets.bottom > 0.1) {
needHideSmiley = false;
setState(() {
emojiShowing = false;
});
}
if (needShowMore && window.viewInsets.bottom <= 0.1) {
needShowMore = false;
setState(() {
moreShow = true;
});
}
if (needHideMore && window.viewInsets.bottom > 0.1) {
needHideMore = false;
setState(() {
moreShow = false;
});
}
}
@override
void dispose() {
super.dispose();
OnChatMsgInstance.instance.onChatMessage = _tempOnChatMessage;
WidgetsBinding.instance.removeObserver(this);
commentFocus.removeListener(_focusNodeListener);
scrollController.dispose();
socketClient.removeCallback(_toUser.mid);
}
void _focusNodeListener() {
/*if (_focusNode.hasFocus || _focusNode.consumeKeyboardToken()){
setState(() {
smileyPadGone = true;
});
}*/
}
///输入框点击事件
_onTextFieldTap() {
if (emojiShowing) {
needHideSmiley = true;
}
if (moreShow) {
needHideMore = true;
}
}
///表情包点击事件
_onSmileyTap() {
if (!emojiShowing && commentFocus.hasFocus && isKeyBoardShow) {
needShowSmiley = true;
commentFocus.unfocus();
} else {
setState(() {
emojiShowing = !emojiShowing;
isKeyBoardShow = emojiShowing;
moreShow = false;
});
}
}
///更多点击事件
_onMoreTap() {
if (!moreShow && commentFocus.hasFocus && isKeyBoardShow) {
needShowMore = true;
commentFocus.unfocus();
} else {
setState(() {
moreShow = !moreShow;
isKeyBoardShow = moreShow;
emojiShowing = false;
});
}
}
///图片/视频选择
Future getImageOrVideo(GalleryMode galleryMode) async {
if (selectCount == 0) return;
mediaPaths.clear();
List<Media> medias = await ImagePickers.pickerPaths(
galleryMode: galleryMode,
selectCount: (galleryMode == GalleryMode.video) ? 1 : selectCount,
showGif: true,
showCamera: false,
compressSize: 500,
uiConfig: UIConfig(
uiThemeColor: Color(0xFFFFFFFF),
),
cropConfig: CropConfig(
enableCrop: false,
width: 200,
height: 200,
),
);
mediaPaths.addAll(medias.map((e) => Medias(e)).toList());
selectCount = 9 - mediaPaths.length;
if (mediaPaths.length > 0) {
if (galleryMode == GalleryMode.image) {
dynamicType = 1;
} else {
dynamicType = 2;
}
List<String> filePath = mediaPaths.map((e) => e.path).toList();
Future.forEach(filePath.toSet(), (path) async {
String fileUrl = await qiniu.uploadFile(apiService, path);
socketClient
.sendMessage(_toUser.mid, fileUrl,
attach: path, msgType: galleryMode == GalleryMode.image ? 2 : 4)
.then((value) {
Message message = value;
messages.insert(0, message);
chatController.clear();
messageShowTime().then((value) {
refreshState();
jumpToBottom();
});
});
});
}
setState(() {});
}
///拍照
openCamera() async {
if (await Permission.camera.isPermanentlyDenied) {
showCupertinoDialog(
context: context,
builder: (context) {
return RequestPermission(
"assets/image/icon_camera_permission_tips.webp",
S.of(context).ninxiangjiquanxianweikaiqi,
S.of(context).weilekaipaizhaoxuanzhetouxiang,
S.of(context).kaiqiquanxian,
(result) async {
if (result) {
await openAppSettings();
}
},
heightRatioWithWidth: 0.82,
);
});
} else if (await Permission.camera.isGranted) {
if (await Permission.storage.isPermanentlyDenied) {
showCupertinoDialog(
context: context,
builder: (context) {
return RequestPermission(
"assets/image/icon_storage_permission_tips.webp",
"您未开启存储权限,请点击开启",
"为了您可以在使用过程中访问您设备上的照片、媒体内容和文件,请您开启存储使用权限",
S.of(context).kaiqiquanxian,
(result) async {
if (result) {
await openAppSettings();
}
},
heightRatioWithWidth: 0.82,
);
});
} else if (await Permission.storage.isGranted) {
Media medias = await ImagePickers.openCamera(
cameraMimeType: CameraMimeType.photo,
cropConfig: CropConfig(
enableCrop: true,
width: 200,
height: 200,
),
compressSize: 500,
);
if (medias == null) return;
String path = medias.path;
String fileUrl = await qiniu.uploadFile(apiService, path);
socketClient
.sendMessage(_toUser.mid, fileUrl, attach: path, msgType: 2)
.then((value) {
Message message = value;
messages.insert(0, message);
chatController.clear();
messageShowTime().then((value) {
refreshState();
jumpToBottom();
});
});
} else {
showCameraTipsAlertDialog(context);
return false;
}
} else {
showCameraTipsAlertDialog(context);
return false;
}
}
///拍照权限说明
showCameraTipsAlertDialog(context) async {
//显示对话框
showDialog(
context: context,
barrierDismissible: false,
barrierColor: null,
builder: (BuildContext context) {
return Column(
children: [
Container(
width: double.infinity,
padding: EdgeInsets.all(15),
margin: EdgeInsets.all(15),
decoration: new BoxDecoration(
color: Colors.white,
borderRadius: BorderRadius.circular(10),
),
child: Row(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Padding(
padding: EdgeInsets.only(
right: 10.w,
),
child: Icon(
Icons.add_photo_alternate_outlined,
color: Colors.black,
size: 22,
)),
Expanded(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
mainAxisSize: MainAxisSize.min,
children: [
Text(
"相机权限使用说明",
style: TextStyle(
fontSize: 18.sp,
fontWeight: MyFontWeight.regular,
color: Colors.black,
),
),
SizedBox(
height: 3.h,
),
Text(
"实现您扫码、拍摄等功能。",
style: TextStyle(
fontSize: 13.sp,
height: 1.2,
fontWeight: MyFontWeight.regular,
color: Colors.black,
),
),
],
),
),
],
),
)
],
mainAxisSize: MainAxisSize.min,
);
},
);
await Permission.camera.request();
Navigator.of(context).pop();
if (await Permission.camera.isGranted) {
openCamera();
}
}
@override
Widget build(BuildContext context) {
double h = MediaQuery.of(context).viewInsets.bottom;
if (h > 0) {
jumpToBottom();
if (keyboard < h) {
keyboard = h;
// setState(() {});
}
}
return GestureDetector(
behavior: HitTestBehavior.translucent,
onTap: () {
FocusScope.of(context).requestFocus(FocusNode());
setState(() {
needShowSmiley = false;
emojiShowing = false;
isKeyBoardShow = emojiShowing;
moreShow = false;
isKeyBoardShow = moreShow;
});
},
child: Scaffold(
// resizeToAvoidBottomInset: false,
backgroundColor: Color(0xFFF6F6F6),
appBar: MyAppBar(
title: _toUser.nickname,
titleColor: Color(0xFF0D0D0D),
titleSize: 17.sp,
leading: true,
leadingColor: Colors.black,
action: GestureDetector(
behavior: HitTestBehavior.opaque,
onTap: () async {
await Navigator.of(context).pushNamed('/router/chat_setting',
arguments: {"userId": _toUser.mid});
page = 0;
refresh().then((value) {
refreshState();
});
},
child: Container(
alignment: Alignment.center,
child: Icon(
Icons.more_horiz,
color: Colors.black,
size: 30,
),
),
),
),
body: Container(
child: Column(
children: [
Expanded(
child: SmartRefresher(
enablePullDown: false,
enablePullUp: true,
header: MyHeader(),
footer: CustomFooter(
loadStyle: LoadStyle.ShowWhenLoading,
builder: (BuildContext context, LoadStatus mode) {
return SizedBox();
},
),
reverse: true,
scrollController: scrollController,
controller: refreshController,
onRefresh: () {
debugPrint("");
},
onLoading: () {
refresh().then((value) {
refreshState();
});
},
child: chatDetailsList(),
),
flex: 1,
),
input(),
],
),
),
),
);
}
///聊天列表
Widget chatDetailsList() {
return ListView.builder(
itemCount: messages.length,
reverse: true,
padding: EdgeInsets.zero,
itemBuilder: (context, position) {
return GestureDetector(
behavior: HitTestBehavior.opaque,
onTap: () {
setState(() {
if (emojiShowing) {
emojiShowing = !emojiShowing;
}
if (moreShow) {
moreShow = !moreShow;
}
});
FocusScope.of(context).requestFocus(FocusNode());
},
child: chatDetailsItem(position),
);
},
);
}
Widget chatDetailsItem(position) {
bool isSelf = messages[position].fromId == selfUserId;
bool isText = messages[position].msgType == 1;
bool isImage = messages[position].msgType == 2;
GlobalKey _buttonKey = GlobalKey();
return Container(
padding: EdgeInsets.only(
top: 16,
bottom: 16,
),
child: Column(
children: [
if (messages[position].showTime)
Text(
// position == messages.length-1
// ?
AppUtils.milliTimeFormatter(DateTime.fromMillisecondsSinceEpoch(
int.parse(messages[position].time)))
// : AppUtils.getTimeDisplay(
// DateTime.fromMillisecondsSinceEpoch(
// int.parse(messages[position].time)),
// DateTime.fromMillisecondsSinceEpoch(
// int.parse(messages[position+1].time)))
,
textAlign: TextAlign.center,
style: TextStyle(
color: Color(0xFFA29E9E),
fontSize: 10.sp,
fontWeight: MyFontWeight.regular,
),
),
// if (messages.indexOf(message) == (messages.length - 1))
// Padding(
// padding: EdgeInsets.only(top: 10.h, bottom: 24.h),
// child: Text(
// "在对方未回复或关注你之前,你只能发送一条信息",
// textAlign: TextAlign.center,
// style: TextStyle(
// color: Color(0xFFA29E9E),
// fontSize: 10.sp,
// fontWeight: MyFontWeight.regular,
// ),
// ),
// ),
// if (messages.indexOf(message) == (messages.length - 1))
// SizedBox(
// height: 16.h,
// ),
/// not self
if (!isSelf && isText)
SizedBox(
height: 10.h,
),
if (!isSelf && isText)
Padding(
padding: EdgeInsets.only(left: 17.w, right: 39.w),
child: Row(
crossAxisAlignment: CrossAxisAlignment.start,
mainAxisAlignment: MainAxisAlignment.center,
children: [
GestureDetector(
behavior: HitTestBehavior.opaque,
onTap: () {
Navigator.of(context).pushNamed(
'/router/personal_page',
arguments: {
"memberId": _toUser?.mid ?? "",
"inletType": 1
},
);
},
child: MImage(
_toUser.avatar,
isCircle: true,
height: 44.h,
width: 44.h,
fit: BoxFit.cover,
errorSrc: "assets/image/default_1.webp",
fadeSrc: "assets/image/default_1.webp",
),
),
SizedBox(
width: 12.w,
),
Expanded(
child: Container(
alignment: Alignment.centerLeft,
child: GestureDetector(
onLongPress: () {
showMessageMenu(context, _buttonKey, messages[position]);
},
child: Container(
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(6),
color: Color(0xFFFFFFFF),
boxShadow: [
BoxShadow(
color: Color(0xFFA8A3A3).withAlpha(12),
offset: Offset(0, 4),
blurRadius: 4,
spreadRadius: 0,
),
],
),
key: _buttonKey,
padding: EdgeInsets.symmetric(
vertical: 8.h,
horizontal: 12.w,
),
child: Text(
tex = messages[position].content,
textAlign: TextAlign.left,
style: TextStyle(
height: 1.2.h,
color: Color(0XFF0D0D0D),
fontSize: 17.sp,
fontWeight: MyFontWeight.medium,
),
),
),
),
),
),
],
),
),
/// self
if (isSelf && isText)
SizedBox(
height: 10.h,
),
if (isSelf && isText)
Padding(
padding: EdgeInsets.only(left: 36.w, right: 16.w),
child: Row(
crossAxisAlignment: CrossAxisAlignment.start,
mainAxisAlignment: MainAxisAlignment.center,
children: [
if (messages[position].state == 3)
Container(
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(100),
color: Color(0xFFFF441A),
),
width: 20,
height: 20,
alignment: Alignment.center,
child: Text(
"!",
textAlign: TextAlign.left,
style: TextStyle(
color: Colors.white,
fontSize: 17.sp,
fontWeight: MyFontWeight.regular,
),
),
),
if (messages[position].state == 3)
SizedBox(
width: 12.w,
),
Expanded(
child: Container(
alignment: Alignment.centerRight,
child: InkWell(
onLongPress: () {
showMessageMenu(context, _buttonKey, messages[position]);
},
child: Container(
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(6),
color: Color(0xFF32A060),
boxShadow: [
BoxShadow(
color: Color(0xFFA8A3A3).withAlpha(12),
offset: Offset(0, 4),
blurRadius: 4,
spreadRadius: 0,
),
],
),
key: _buttonKey,
padding: EdgeInsets.symmetric(
vertical: 8.h,
horizontal: 12.w,
),
child: Text(
tex = messages[position].content,
textAlign: TextAlign.left,
style: TextStyle(
height: 1.2.h,
color: Colors.white,
fontSize: 17.sp,
fontWeight: MyFontWeight.medium,
),
),
),
),
),
),
SizedBox(
width: 12.w,
),
GestureDetector(
behavior: HitTestBehavior.opaque,
onTap: () {
Navigator.of(context).pushNamed(
'/router/personal_page',
arguments: {
"memberId": "0",
"inletType": 1,
},
);
},
child: MImage(
userInfo?.headimg ?? "",
isCircle: true,
height: 44.h,
width: 44.h,
fit: BoxFit.cover,
errorSrc: "assets/image/default_1.webp",
fadeSrc: "assets/image/default_1.webp",
),
),
],
),
),
/// not self image 图片
if (!isSelf && isImage)
Padding(
padding: EdgeInsets.only(left: 17.w, right: 39.w, top: 20.h),
child: Row(
children: [
MImage(
userInfo?.headimg ?? "",
isCircle: true,
width: 44,
height: 44,
fit: BoxFit.cover,
errorSrc: "assets/image/default_1.webp",
fadeSrc: "assets/image/default_1.webp",
),
SizedBox(
width: 12.w,
),
GestureDetector(
onLongPress: () {
showMessageMenu(context, _buttonKey, messages[position]);
},
onTap: () {
if (imageUrl.contains(messages[position].attach)) {
ImagePickers.previewImages(imageUrl, imageUrl.indexOf(messages[position].attach));
}
},
child: FutureBuilder(
future: fetchImageSize(messages[position]),
key: _buttonKey,
builder: (BuildContext context, AsyncSnapshot snapshot) {
if (snapshot.connectionState ==
ConnectionState.waiting ||
snapshot.hasError) {
return Image.file(
File(messages[position].attach),
width: 180.w,
height: 200.h,
alignment: Alignment.centerLeft,
fit: BoxFit.contain,
);
} else {
return Image.file(
File(messages[position].attach),
width: snapshot.data.width,
height: snapshot.data.height,
alignment: Alignment.centerLeft,
fit: BoxFit.cover,
);
}
},
),
),
Spacer(),
],
),
),
/// self image 图片
if (isSelf && isImage)
Padding(
padding: EdgeInsets.only(
left: 39.w,
right: 17.w,
top: 20.h,
),
child: Row(
children: [
Spacer(),
GestureDetector(
onLongPress: () {
showMessageMenu(context, _buttonKey, messages[position]);
},
onTap: () {
debugPrint("imageUrl: ${imageUrl}");
if (imageUrl.contains(messages[position].attach)) {
ImagePickers.previewImages(imageUrl, imageUrl.indexOf(messages[position].attach));
}
},
child: FutureBuilder (
future: fetchImageSize(messages[position]),
key: _buttonKey,
builder: (BuildContext context, AsyncSnapshot snapshot) {
if (snapshot.connectionState == ConnectionState.waiting || snapshot.hasError) {
return Image.file(
File(messages[position].attach),
width: 180.w,
height: 200.h,
alignment: Alignment.centerRight,
fit: BoxFit.contain,
);
} else {
return Image.file(
File(messages[position].attach),
width: snapshot.data.width,
height: snapshot.data.height,
alignment: Alignment.centerRight,
fit: BoxFit.contain,
);
}
},
),
),
SizedBox(
width: 12.w,
),
MImage(
userInfo?.headimg ?? "",
isCircle: true,
width: 44,
height: 44,
fit: BoxFit.cover,
errorSrc: "assets/image/default_1.webp",
fadeSrc: "assets/image/default_1.webp",
),
],
),
),
/// no reply long time
// if (messages.indexOf(message) == 0)
// Padding(
// padding: EdgeInsets.only(left: 17.w, right: 17.w, top: 24.h),
// child: Text(
// "由于对方没有回复你,你只能发送一条消息,需要对方关注或回复后才能恢复正常聊天",
// textAlign: TextAlign.center,
// style: TextStyle(
// color: Color(0xFFA29E9E),
// fontSize: 10.sp,
// fontWeight: MyFontWeight.regular,
// ),
// ),
// ),
],
),
);
}
/// 显示消息菜单
showMessageMenu(context, _buttonKey, message) {
RenderBox renderBox = _buttonKey.currentContext.findRenderObject() as RenderBox;
Offset buttonPosition = renderBox.localToGlobal(Offset.zero);
Size buttonSize = renderBox.size;
showMenu(
context: context, ///去除阴影
elevation: 0,
color: Colors.transparent,
position: RelativeRect.fromLTRB(
buttonPosition.dx + (buttonSize.width - 180.w) / 2, // 居中对齐
buttonPosition.dy - 68,
buttonPosition.dx + buttonSize.width,
buttonPosition.dy,
),
/// 设置弹出菜单的显示位置
items: [
PopupMenuItem(
value: 1,
padding: EdgeInsets.zero,
child: Stack(
alignment: Alignment.bottomCenter,
children: [
Container(
padding: EdgeInsets.only(bottom: 13.h),
child: Container(
width: 180.w,
decoration: BoxDecoration(
color: Color(0xFF2A2A2A),
borderRadius: BorderRadius.circular(6),
),
padding: EdgeInsets.symmetric(
horizontal: 32.w,
vertical: 7.5.h,
),
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
crossAxisAlignment: CrossAxisAlignment.center,
children: [
GestureDetector(
onTap: () {
setState(() {
this.copy(message.content);
Navigator.pop(context);
});
},
child: Column(
children: [
Image.asset(
"assets/image/icon_chat_copy.webp",
height: 16,
width: 16,
),
SizedBox(
height: 2.h,
),
Text(
"复制",
textAlign:
TextAlign.center,
style: TextStyle(
color: Colors.white,
fontSize: 12.sp,
fontWeight: MyFontWeight
.regular,
),
),
],
),
),
GestureDetector(
onTap: () async {
await hxDatabase.deleteByMsgId("${message.id}");
messages.remove(message);
Navigator.pop(context);
if (mounted) {
setState(() {});
}
},
child: Column(
children: [
Image.asset(
"assets/image/icon_chat_delete.webp",
height: 16,
width: 16,
),
SizedBox(
height: 2.h,
),
Text(
S.of(context).shanchu,
textAlign: TextAlign.center,
style: TextStyle(
color: Colors.white,
fontSize: 12.sp,
fontWeight: MyFontWeight.regular,
),
),
],
),
),
],
),
),
),
Image.asset(
"assets/image/icon_copy_j.webp",
height: 17,
width: 17,
),
],
),
),
],
);
}
Future<Size> fetchImageSize(Message message) async {
String imageLocalPath = message.attach;
String imageUrl = message.content;
debugPrint("$imageLocalPath");
debugPrint("$imageUrl");
File file = File(imageLocalPath);
if (!(await file.exists())) {
await qiniu.downloadFile(imageUrl, savePath: imageLocalPath);
}
Size size = Size.zero;
if (sharedPre != null) {
String sizeStr = sharedPre.getString(imageLocalPath);
if (sizeStr != null && sizeStr != "") {
Map<String, dynamic> sizeMap = jsonDecode(sizeStr);
size = Size(sizeMap["width"], sizeMap["height"]);
if (size != Size.zero) {
return size;
}
}
}
Completer<Size> completer = Completer();
Image.file(file)
.image
.resolve(ImageConfiguration())
.addListener(ImageStreamListener((image, synchronousCall) {
size = Size((image.image.width ?? 0).toDouble(),
(image.image.height ?? 0).toDouble());
size = resizeImage(size);
Map<String, double> sizeMap = {
"width": size.width,
"height": size.height,
};
sharedPre.setString(imageLocalPath, jsonEncode(sizeMap));
completer.complete(size);
}));
return completer.future;
}
resizeImage(Size size) {
if (size.width > 180 || size.height > 200) {
if (size.width > size.height) {
int height = size.height ~/ (size.width ~/ 180);
size = Size(180, height.toDouble());
} else {
int width = size.width ~/ (size.height ~/ 200);
size = Size(width.toDouble(), 200);
}
}
return size;
}
///富文本输入框
Widget input() {
return Container(
color: Color(0xFFFDFCFC),
padding: EdgeInsets.only(top: 14.h, bottom: 15.h),
child: Column(
children: [
///输入框
Row(
children: [
Expanded(
flex: 1,
child: Container(
margin: EdgeInsets.only(
left: 20.w,
),
decoration: BoxDecoration(
color: Color(0xFFF6F6F6),
borderRadius: BorderRadius.circular(6),
),
child: Container(
margin: EdgeInsets.only(left: 17.w),
alignment: Alignment.topLeft,
child: TextField(
textInputAction: TextInputAction.send,
onTap: () {
moreShow = false;
_onTextFieldTap();
},
onEditingComplete: () {
var commentText = chatController.text;
if (commentText.trim() == "") {
return;
}
socketClient
.sendMessage(_toUser.mid, commentText)
.then((value) {
Message message = value;
messages.insert(0, message);
chatController.clear();
messageShowTime().then((value) {
refreshState();
jumpToBottom();
});
});
},
maxLines: 8,
minLines: 1,
focusNode: commentFocus,
controller: chatController,
decoration: InputDecoration(
border: InputBorder.none,
hintText: hintText,
hintStyle: TextStyle(
fontSize: 14.sp,
color: Color(0xFF868686),
),
),
),
),
),
),
GestureDetector(
behavior: HitTestBehavior.opaque,
onTap: () {
_onSmileyTap();
jumpToBottom();
},
child: Container(
padding: EdgeInsets.only(left: 15.w, right: 8.w),
child: Image.asset(
"assets/image/icon_chat_emo.webp",
height: 26.h,
width: 26.h,
),
),
),
GestureDetector(
behavior: HitTestBehavior.opaque,
onTap: () {
_onMoreTap();
jumpToBottom();
},
child: Container(
padding: EdgeInsets.only(left: 8.w, right: 19.w),
child: Image.asset(
"assets/image/chat_more.webp",
height: 26.h,
width: 26.h,
),
),
),
],
),
SizedBox(
height: 16.h,
),
///表情
Offstage(
offstage: !emojiShowing,
child: SizedBox(
height: keyboard == -1 ? 270 : keyboard,
width: MediaQuery.of(context).size.width,
child: EmojiPicker(
textEditingController: chatController,
config: Config(
columns: 7,
emojiSizeMax: 32 * (Platform.isIOS ? 1.10 : 1.0),
verticalSpacing: 0,
horizontalSpacing: 0,
gridPadding: EdgeInsets.zero,
initCategory: Category.RECENT,
bgColor: const Color(0xFFF2F2F2),
// indicatorColor: Colors.blue,
iconColor: Colors.grey,
iconColorSelected: Colors.blue,
backspaceColor: Colors.blue,
skinToneDialogBgColor: Colors.white,
skinToneIndicatorColor: Colors.grey,
enableSkinTones: true,
showRecentsTab: true,
recentsLimit: 28,
replaceEmojiOnLimitExceed: false,
noRecents: Text(
"最近使用",
style: TextStyle(fontSize: 20, color: Colors.black26),
textAlign: TextAlign.center,
),
loadingIndicator: const SizedBox.shrink(),
tabIndicatorAnimDuration: Duration(milliseconds: 0),
categoryIcons: const CategoryIcons(),
buttonMode: ButtonMode.MATERIAL,
checkPlatformCompatibility: true,
),
),
),
),
///更多
Offstage(
offstage: !moreShow,
child: Container(
height: keyboard == -1 ? 167.h : keyboard,
child: Column(
children: [
Container(
width: double.infinity,
height: 1.h,
color: Color(0xFFF7F7F7),
margin: EdgeInsets.only(bottom: 10.h),
),
Row(
children: [
GestureDetector(
behavior: HitTestBehavior.opaque,
onTap: () {
openCamera();
},
child: Column(
children: [
Container(
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(6),
color: Color(0xFFFFFFFF),
boxShadow: [
BoxShadow(
color: Color(0xFFD5D5D5).withAlpha(25),
offset: Offset(4, 2),
blurRadius: 4,
spreadRadius: 0,
)
],
),
margin: EdgeInsets.only(right: 15.w, left: 14.w),
padding: EdgeInsets.all(12),
child: Image.asset(
"assets/image/icon_chat_camera.webp",
height: 24,
width: 24,
),
),
Padding(
padding: EdgeInsets.only(top: 8.h),
child: Text(
"拍照",
style: TextStyle(
fontSize: 12.sp,
color: Color(0xFFA29E9E),
fontWeight: MyFontWeight.regular,
),
),
),
],
),
),
GestureDetector(
behavior: HitTestBehavior.opaque,
onTap: () {
getImageOrVideo(GalleryMode.image);
},
child: Column(
children: [
Container(
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(6),
color: Color(0xFFFFFFFF),
boxShadow: [
BoxShadow(
color: Color(0xFFD5D5D5).withAlpha(25),
offset: Offset(4, 2),
blurRadius: 4,
spreadRadius: 0,
)
],
),
padding: EdgeInsets.all(12),
child: Image.asset(
"assets/image/icon_chat_photo.webp",
height: 24,
width: 24,
),
),
Padding(
padding: EdgeInsets.only(top: 8.h),
child: Text(
"相册",
style: TextStyle(
fontSize: 12.sp,
color: Color(0xFFA29E9E),
fontWeight: MyFontWeight.regular,
),
),
),
],
),
),
],
),
],
),
),
),
],
),
);
}
/// 复制文本
copy(String tex) {
debugPrint(tex);
Clipboard.setData(ClipboardData(text: tex));
}
}