일대일 채팅, 그룹 채팅, 메시지 반응, 응답 메시지, 링크 미리 보기 및 전체 보기 구성과 같은 고도의 사용자 정의 옵션과 Chat View를 통합할 수 있는 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 | 맥OS | 편물 | 리눅스 | 윈도우 |
---|---|---|---|---|---|---|
문자 메시지 | ✔️ | ✔️ | ✔️ | ✔️ | ✔️ | ✔️ |
이미지 메시지 | ✔️ | ✔️ | ✔️ | ✔️ | ✔️ | ✔️ |
음성 메시지 | ✔️ | ✔️ | ||||
맞춤 메시지 | ✔️ | ✔️ | ✔️ | ✔️ | ✔️ | ✔️ |
<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
클래스를 사용하여 링크 미리보기 구성을 추가합니다. 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
플래그가 추가되었습니다. 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
),
ChatBackgroundConfiguration
에서 메시지를 정렬하기 위해 콜백 messageSorter
추가했습니다. 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,
),
...
),
더 나은 이해와 기본 구현을 보려면 블로그를 확인하세요.
또한 전체 예를 보려면 example 디렉터리에 있는 예제 앱을 확인하거나 pub.dartlang.org의 'Example' 탭에서 더 완전한 예를 확인하세요.
바살 타나 | 드바니트 바가니 | 우자스 마지티야 | 아푸르바 칸트라비야 | 아디트야 차브다 |
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.