flutter_chatview
2.4.0
一个 Flutter 包,允许您将聊天视图与高度自定义的选项集成,例如一对一聊天、群聊、消息反应、回复消息、链接预览和整体视图配置。
如需网络演示,请访问聊天视图示例。
在Message
类中将sendBy
字段重命名为sentBy
。
在ChatController
类中将chatUsers
字段重命名为otherUsers
。
将currentUser
字段从ChatView
小部件移动到ChatController
类
更新了Message
的copyWith
方法中的id
值以具有正确的值。
从ChatView
中删除了showTypingIndicator
字段,并将其替换为ChatController.showTypingIndicator
。
前:
ChatView (
showTypingIndicator : false ,
),
后:
/// use it with your [ChatController] instance.
_chatContoller.setTypingIndicator = true ; // for showing indicator
_chatContoller.setTypingIndicator = false ; // for hiding indicator
更新了ChatUser
、 Message
和ReplyMessage
数据模型的fromJson
和toJson
方法:
ChatUser.fromJson
中:前:
ChatUser . fromJson (
{
...
'imageType' : ImageType .asset,
...
},
),
后:
ChatUser . fromJson (
{
...
'imageType' : 'asset' ,
...
},
),
ChatUser.toJson
中:前:
{
...
imageType : ImageType .asset,
...
}
后:
{
...
imageType : asset,
...
}
Message.fromJson
中:前:
Message . fromJson (
{
...
'createdAt' : DateTime . now (),
'message_type' : MessageType .text,
'voice_message_duration' : Duration (seconds : 5 ),
...
}
)
后:
Message . fromJson (
{
...
'createdAt' : '2024-06-13T17:32:19.586412' ,
'message_type' : 'text' ,
'voice_message_duration' : '5000000' ,
...
}
)
Message.toJson
中:前:
{
...
createdAt : 2024 - 06 - 13 17 : 23 : 19.454789 ,
message_type : MessageType .text,
voice_message_duration : 0 : 00 : 05.000000 ,
...
}
后:
{
...
createdAt : 2024 - 06 - 13T17 : 32 : 19.586412 ,
message_type : text,
voice_message_duration : 5000000 ,
...
}
ReplyMessage.fromJson
中:前:
ReplyMessage . fromJson (
{
...
'message_type' : MessageType .text,
'voiceMessageDuration' : Duration (seconds : 5 ),
...
}
)
后:
ReplyMessage . fromJson (
{
...
'message_type' : 'text' ,
'voiceMessageDuration' : '5000000' ,
...
}
)
在ReplyMessage.toJson
中:
前:
{
...
message_type : MessageType .text,
voiceMessageDuration : 0 : 00 : 05.000000 ,
...
}
后:
{
...
message_type : text,
voiceMessageDuration : 5000000 ,
...
}
pubspec.yaml
dependencies :
chatview : < latest - version >
在 pub.dev 的“安装”选项卡中获取最新版本
import 'package:chatview/chatview.dart' ;
final chatController = ChatController (
initialMessageList : messageList,
scrollController : ScrollController (),
currentUser : ChatUser (id : '1' , name : 'Flutter' ),
otherUsers : [ ChatUser (id : '2' , name : 'Simform' )],
);
ChatView
小部件。 ChatView (
chatController : chatController,
onSendTap : onSendTap,
chatViewState : ChatViewState .hasMessages, // Add this state once data is available.
)
Message
类的 messageList。 List < Message > messageList = [
Message (
id : '1' ,
message : "Hi" ,
createdAt : createdAt,
sentBy : userId,
),
Message (
id : '2' ,
message : "Hello" ,
createdAt : createdAt,
sentBy : userId,
),
];
onSendTap
。 void onSendTap ( String message, ReplyMessage replyMessage, MessageType messageType){
final message = Message (
id : '3' ,
message : "How are you" ,
createdAt : DateTime . now (),
sentBy : currentUser.id,
replyMessage : replyMessage,
messageType : messageType,
);
chatController. addMessage (message);
}
注意:您可以从messageType
参数评估消息类型,基于此您可以执行操作。
消息类型 | 安卓 | iOS系统 | 苹果系统 | 网络 | Linux | 视窗 |
---|---|---|---|---|---|---|
短信 | ✔️ | ✔️ | ✔️ | ✔️ | ✔️ | ✔️ |
图片信息 | ✔️ | ✔️ | ✔️ | ✔️ | ✔️ | ✔️ |
语音留言 | ✔️ | ✔️ | ||||
自定义消息 | ✔️ | ✔️ | ✔️ | ✔️ | ✔️ | ✔️ |
<project root>/ios/Runner/Info.plist
的Info.plist文件中: <key>NSCameraUsageDescription</key>
<string>Used to demonstrate image picker plugin</string>
<key>NSMicrophoneUsageDescription</key>
<string>Used to capture audio for image picker plugin</string>
<key>NSPhotoLibraryUsageDescription</key>
<string>Used to demonstrate image picker plugin</string>
ios/Runner/Info.plist
中添加这两行 <key>NSMicrophoneUsageDescription</key>
<string>This app requires Mic permission.</string>
Podfile
中添加这一行 platform :ios, '10.0'
minSdkVersion 21
AndroidManifest.xml
中添加RECORD_AUDIO权限 <uses-permission android:name="android.permission.RECORD_AUDIO"/>
FeatureActiveConfig
启用和禁用特定功能。 ChatView (
...
featureActiveConfig : FeatureActiveConfig (
enableSwipeToReply : true ,
enableSwipeToSeeTime : false ,
),
...
)
ChatViewAppBar
添加应用栏。 ChatView (
...
appBar : ChatViewAppBar (
profilePicture : profileImage,
chatTitle : "Simform" ,
userStatus : "online" ,
actions : [
Icon ( Icons .more_vert),
],
),
...
)
ChatBackgroundConfiguration
类添加消息列表配置。 ChatView (
...
chatBackgroundConfig : ChatBackgroundConfiguration (
backgroundColor : Colors .white,
backgroundImage : backgroundImage,
),
...
)
SendMessageConfiguration
类添加发送消息配置。 ChatView (
...
sendMessageConfig : SendMessageConfiguration (
replyMessageColor : Colors .grey,
replyDialogColor : Colors .blue,
replyTitleColor : Colors .black,
closeIconColor : Colors .black,
),
...
)
ChatBubbleConfiguration
类添加聊天气泡配置。 ChatView (
...
chatBubbleConfig : ChatBubbleConfiguration (
onDoubleTap : (){
// Your code goes here
},
outgoingChatBubbleConfig : ChatBubble ( // Sender's message chat bubble
color : Colors .blue,
borderRadius : const BorderRadius . only (
topRight : Radius . circular ( 12 ),
topLeft : Radius . circular ( 12 ),
bottomLeft : Radius . circular ( 12 ),
),
),
inComingChatBubbleConfig : ChatBubble ( // Receiver's message chat bubble
color : Colors .grey.shade200,
borderRadius : const BorderRadius . only (
topLeft : Radius . circular ( 12 ),
topRight : Radius . circular ( 12 ),
bottomRight : Radius . circular ( 12 ),
),
),
)
...
)
SwipeToReplyConfiguration
类添加滑动以回复配置。 ChatView (
...
swipeToReplyConfig : SwipeToReplyConfiguration (
onLeftSwipe : (message, sentBy){
// Your code goes here
},
onRightSwipe : (message, sentBy){
// Your code goes here
},
),
...
)
MessageConfiguration
类添加消息配置。 ChatView (
...
messageConfig : MessageConfiguration (
messageReactionConfig : MessageReactionConfiguration (), // Emoji reaction configuration for single message
imageMessageConfig : ImageMessageConfiguration (
onTap : (){
// Your code goes here
},
shareIconConfig : ShareIconConfiguration (
onPressed : (){
// Your code goes here
},
),
),
),
...
)
ReactionPopupConfiguration
类添加反应弹出配置。 ChatView (
...
reactionPopupConfig : ReactionPopupConfiguration (
backgroundColor : Colors .white,
userReactionCallback : (message, emoji){
// Your code goes here
}
padding : EdgeInsets . all ( 12 ),
shadow : BoxShadow (
color : Colors .black54,
blurRadius : 20 ,
),
),
...
)
ReplyPopupConfiguration
类添加回复弹出窗口配置。 ChatView (
...
replyPopupConfig : ReplyPopupConfiguration (
backgroundColor : Colors .white,
onUnsendTap : (message){ // message is 'Message' class instance
// Your code goes here
},
onReplyTap : (message){ // message is 'Message' class instance
// Your code goes here
},
onReportTap : (){
// Your code goes here
},
onMoreTap : (){
// Your code goes here
},
),
...
)
RepliedMessageConfiguration
类添加回复消息配置。 ChatView (
...
repliedMessageConfig : RepliedMessageConfiguration (
backgroundColor : Colors .blue,
verticalBarColor : Colors .black,
repliedMsgAutoScrollConfig : RepliedMsgAutoScrollConfig (),
),
...
)
typeIndicatorConfig
和TypeIndicatorConfig
。 ChatView (
...
typeIndicatorConfig : TypeIndicatorConfiguration (
flashingCircleBrightColor : Colors .grey,
flashingCircleDarkColor : Colors .black,
),
...
)
ChatController.setTypingIndicaor
,有关详细信息,请参阅ChatController
。 /// use it with your [ChatController] instance.
_chatContoller.setTypingIndicator = true ; // for showing indicator
_chatContoller.setTypingIndicator = false ; // for hiding indicator
LinkPreviewConfiguration
类添加 linkpreview 配置。 ChatView (
...
chatBubbleConfig : ChatBubbleConfiguration (
linkPreviewConfig : LinkPreviewConfiguration (
linkStyle : const TextStyle (
color : Colors .white,
decoration : TextDecoration .underline,
),
backgroundColor : Colors .grey,
bodyStyle : const TextStyle (
color : Colors .grey.shade200,
fontSize : 16 ,
),
titleStyle : const TextStyle (
color : Colors .black,
fontSize : 20 ,
),
),
)
...
)
ChatView (
...
isLastPage : false ,
featureActiveConfig : FeatureActiveConfig (
enablePagination : true ,
),
loadMoreData : chatController.loadMoreData,
...
)
ChatView (
...
sendMessageConfig : SendMessageConfiguration (
enableCameraImagePicker : false ,
enableGalleryImagePicker : true ,
imagePickerIconsConfig : ImagePickerIconsConfiguration (
cameraIconColor : Colors .black,
galleryIconColor : Colors .black,
)
)
...
)
ChatViewState
自定义。 ChatView (
...
chatViewStateConfig : ChatViewStateConfiguration (
loadingWidgetConfig : ChatViewStateWidgetConfiguration (
loadingIndicatorColor : Colors .pink,
),
onReloadButtonTap : () {},
),
...
)
RepliedMsgAutoScrollConfig
类设置自动滚动和突出显示配置。 ChatView (
...
repliedMsgAutoScrollConfig : RepliedMsgAutoScrollConfig (
enableHighlightRepliedMsg : true ,
highlightColor : Colors .grey,
highlightScale : 1.1 ,
)
...
)
TextFieldConfiguration
中输入时的回调 ChatView (
...
sendMessageConfig : SendMessageConfiguration (
textFieldConfig : TextFieldConfiguration (
onMessageTyping : (status) {
// send composing/composed status to other client
// your code goes here
},
/// After typing stopped, the threshold time after which the composing
/// status to be changed to [TypeWriterStatus.typed] .
/// Default is 1 second.
compositionThresholdTime : const Duration (seconds : 1 ),
),
...
)
)
ReceiptsWidgetConfig
。 ChatView (
...
featureActiveConfig : const FeatureActiveConfig (
/// Controls the visibility of message seen ago receipts default is true
lastSeenAgoBuilderVisibility : false ,
/// Controls the visibility of the message [receiptsBuilder]
receiptsBuilderVisibility : false ),
ChatBubbleConfiguration (
inComingChatBubbleConfig : ChatBubble (
onMessageRead : (message) {
/// send your message reciepts to the other client
debugPrint ( 'Message Read' );
},
),
outgoingChatBubbleConfig : ChatBubble (
receiptsWidgetConfig : ReceiptsWidgetConfig (
/// custom receipts builder
receiptsBuilder : _customReceiptsBuilder,
/// whether to display receipts in all
/// message or just at the last one just like instagram
showReceiptsIn : ShowReceiptsIn .lastMessage
),
),
),
...
)
enableOtherUserName
以在聊天中隐藏用户名。 ChatView (
...
featureActiveConfig : const FeatureActiveConfig (
enableOtherUserName : false ,
),
...
)
onMoreTap
和onReportTap
回调。 ChatView (
...
replyPopupConfig : ReplyPopupConfiguration (
onReportTap : ( Message message) {
debugPrint ( 'Message: $ message ' );
},
onMoreTap : ( Message message, bool sentByCurrentUser) {
debugPrint ( 'Message : $ message ' );
},
),
...
)
emojiPickerSheetConfig
用于配置表情符号选择器表。 ChatView (
...
emojiPickerSheetConfig : Config (
emojiViewConfig : EmojiViewConfig (
columns : 7 ,
emojiSizeMax : 32 ,
recentsLimit : 28 ,
backgroundColor : Colors .white,
),
categoryViewConfig : const CategoryViewConfig (
initCategory : Category . RECENT ,
recentTabBehavior : RecentTabBehavior . NONE ,
),
...
)
VoiceRecordingConfiguration
配置样式和录音质量。 ChatView (
...
sendMessageConfig : SendMessageConfiguration (
voiceRecordingConfiguration : VoiceRecordingConfiguration (
iosEncoder : IosEncoder .kAudioFormatMPEG4AAC,
androidOutputFormat : AndroidOutputFormat .mpeg4,
androidEncoder : AndroidEncoder .aac,
bitRate : 128000 ,
sampleRate : 44100 ,
waveStyle : WaveStyle (
showMiddleLine : false ,
waveColor : theme.waveColor ?? Colors .white,
extendWaveform : true ,
),
),
...
)
)
enabled
以启用/禁用聊天文本字段。 ChatView (
...
sendMessageConfig : SendMessageConfiguration (
...
textFieldConfig : TextFieldConfig (
enabled : true // [false] to disable text field.
),
...
),
...
)
isProfilePhotoInBase64
,用于定义提供的图像是 url 还是 base64 数据。 final chatController = ChatController (
...
chatUsers : [
ChatUser (
id : '1' ,
name : 'Simform' ,
isProfilePhotoInBase64 : false ,
profilePhoto : 'ImageNetworkUrl' ,
),
],
...
);
ChatView (
...
profileCircleConfig : const ProfileCircleConfiguration (
isProfilePhotoInBase64 : false ,
profileImageUrl : 'ImageNetworkUrl' ,
),
...
)
DefaultGroupSeparatorConfiguration
中添加了chatSeparatorDatePattern
,以使用提供的模式分隔聊天。 ChatView (
...
chatBackgroundConfig : ChatBackgroundConfiguration (
...
defaultGroupSeparatorConfig : DefaultGroupSeparatorConfiguration (
chatSeparatorDatePattern : 'MMM dd, yyyy'
),
...
),
...
)
cancelRecordConfiguration
提供取消语音记录消息的配置。 ChatView (
...
sendMessageConfig : SendMessageConfiguration (
...
cancelRecordConfiguration : CancelRecordConfiguration (
icon : const Icon (
Icons .cancel_outlined,
),
onCancel : () {
debugPrint ( 'Voice recording cancelled' );
},
iconColor : Colors .black,
),
...
),
...
)
reactedUserCallback
的反应用户列表中添加了 onTap 回调。 ChatView (
...
messageConfig : MessageConfiguration (
...
messageReactionConfig : MessageReactionConfiguration (
reactionsBottomSheetConfig : ReactionsBottomSheetConfiguration (
reactedUserCallback : (reactedUser, reaction) {
debugPrint (reaction);
},
),
),
...
),
...
),
customMessageReplyViewBuilder
来自定义自定义类型消息的回复消息视图。 ChatView (
...
messageConfig : MessageConfiguration (
customMessageBuilder : ( ReplyMessage state) {
return Text (
state.message,
maxLines : 1 ,
overflow : TextOverflow .ellipsis,
style : const TextStyle (
fontSize : 12 ,
color : Colors .black,
),
);
},
),
...
)
defaultAvatarImage
、资产和网络配置文件图像的错误生成器assetImageErrorBuilder
networkImageErrorBuilder
、Enum ImageType
以将图像定义为资产、网络或 base64 数据。 ChatView (
...
appBar : ChatViewAppBar (
defaultAvatarImage : defaultAvatar,
imageType : ImageType .network,
networkImageErrorBuilder : (context, url, error) {
return Center (
child : Text ( 'Error $ error ' ),
);
},
assetImageErrorBuilder : (context, error, stackTrace) {
return Center (
child : Text ( 'Error $ error ' ),
);
},
),
...
),
customMessageReplyViewBuilder
来自定义自定义类型消息的回复消息视图。 ChatView (
...
messageConfig : MessageConfiguration (
customMessageBuilder : ( ReplyMessage state) {
return Text (
state.message,
maxLines : 1 ,
overflow : TextOverflow .ellipsis,
style : const TextStyle (
fontSize : 12 ,
color : Colors .black,
),
);
},
),
...
)
replyMessageBuilder
来自定义回复的视图。 ChatView (
...
replyMessageBuilder : (context, state) {
return Container (
decoration : const BoxDecoration (
color : Colors .white,
borderRadius : BorderRadius . vertical (
top : Radius . circular ( 14 ),
),
),
margin : const EdgeInsets . only (
bottom : 17 ,
right : 0.4 ,
left : 0.4 ,
),
padding : const EdgeInsets . fromLTRB ( 10 , 10 , 10 , 30 ),
child : Container (
padding : const EdgeInsets . symmetric (
horizontal : 6 ,
),
decoration : BoxDecoration (
color : Colors .grey.shade200,
borderRadius : BorderRadius . circular ( 12 ),
),
child : Column (
mainAxisSize : MainAxisSize .min,
children : [
Row (
mainAxisAlignment : MainAxisAlignment .spaceBetween,
children : [
Expanded (
child : Text (
state.message,
maxLines : 1 ,
overflow : TextOverflow .ellipsis,
style : const TextStyle (
fontWeight : FontWeight .bold,
),
),
),
IconButton (
constraints : const BoxConstraints (),
padding : EdgeInsets .zero,
icon : const Icon (
Icons .close,
size : 16 ,
),
onPressed : () => ChatView . closeReplyMessageView (context),
),
],
),
],
),
),
);
},
...
)
_chatController. addReplySuggestions ([
SuggestionItemData (text : 'Thanks.' ),
SuggestionItemData (text : 'Thank you very much.' ),
SuggestionItemData (text : 'Great.' )
]);
_chatController. removeReplySuggestions ();
replySuggestionsConfig : ReplySuggestionsConfig (
itemConfig : SuggestionItemConfig (
decoration : BoxDecoration (),
textStyle : TextStyle (),
padding : EdgetInsets . all ( 8 ),
customItemBuilder : (index, suggestionItemData) => Container ()
),
listConfig : SuggestionListConfig (
decoration : BoxDecoration (),
padding : EdgetInsets . all ( 8 ),
itemSeparatorWidth : 8 ,
axisAlignment : SuggestionListAlignment .left
)
onTap : (item) =>
_onSendTap (item.text, const ReplyMessage (), MessageType .text),
autoDismissOnSelection : true
),
messageSorter
以对ChatBackgroundConfiguration
中的消息进行排序。 ChatView (
...
chatBackgroundConfig : ChatBackgroundConfiguration (
...
messageSorter : (message1, message2) {
return message1.createdAt. compareTo (message2.createdAt);
}
...
),
...
),
ScrollToBottomButtonConfig
更改滚动到底部按钮的配置。 ChatView (
...
scrollToBottomButtonConfig : ScrollToBottomButtonConfig (
),
...
),
errorBody
在无法解析链接进行预览时显示错误消息。 ChatView (
...
linkPreviewConfig : LinkPreviewConfiguration (
errorBody : 'Error encountered while parsing the link for preview'
),
...
),
suggestionItemType
以多行而不是可滚动的形式显示建议项。 ChatView (
...
replySuggestionsConfig : ReplySuggestionsConfig (
suggestionItemType : SuggestionItemsType .multiline,
),
...
),
查看博客以更好地理解和基本实现。
另外,对于整个示例,请查看示例目录中的示例应用程序或 pub.dartlang.org 上的“示例”选项卡以获取更完整的示例。
瓦萨尔塔纳 | 德瓦尼特·瓦加尼 | 乌贾斯·马吉蒂亚 | 阿普尔瓦·坎特拉维亚 | 阿迪亚查夫达 |
MIT License
Copyright (c) 2022 Simform Solutions
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.