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.