StreamChatClient class

The official Dart client for Stream Chat, a service for building chat applications. This library can be used on any Dart project and on both mobile and web apps with Flutter.

You can sign up for a Stream account at https://getstream.io/chat/

The Chat client will manage API call, event handling and manage the websocket connection to Stream Chat servers.

final client = StreamChatClient("stream-chat-api-key");
Available extensions

Constructors

StreamChatClient(String apiKey, {Level logLevel = Level.WARNING, LogHandlerFunction logHandlerFunction = StreamChatClient.defaultLogHandler, RetryPolicy? retryPolicy, String? baseURL, String? baseWsUrl, Duration connectTimeout = kDefaultConnectTimeout, Duration receiveTimeout = kDefaultReceiveTimeout, StreamChatApi? chatApi, WebSocket? ws, AttachmentFileUploaderProvider attachmentFileUploaderProvider = StreamAttachmentFileUploader.new, Iterable<Interceptor>? chatApiInterceptors, HttpClientAdapter? httpClientAdapter, bool recoverStateOnReconnect = true, bool isLocalUnreadCountEnabled = false})
Create a client instance with default options. You should only create the client once and re-use it across your application.

Properties

appSettings AppSettings
The cached AppSettings for this client.
no setter
channelDeliveryReporter ChannelDeliveryReporter
Manages delivery receipt reporting for channel messages.
latefinal
chatPersistenceClient ChatPersistenceClient?
Chat persistence client
getter/setter pair
eventStream Stream<Event>
Stream of Event coming from _ws connection Listen to this or use the on method to filter specific event types
no setter
hashCode int
The hash code for this object.
no setterinherited
isLocalUnreadCountEnabled bool
Whether the SDK should track unread counts locally, on-device, for channels that have read events disabled (e.g. livestream channel types).
final
logger Logger
Client specific logger instance. Refer to the class Logger to learn more about the specific implementation.
latefinal
logHandlerFunction LogHandlerFunction
A function that has a parameter of type LogRecord. This is called on every new log record. By default the client will use the handler returned by _getDefaultLogHandler. Setting it you can handle the log messages directly instead of have them written to stdout, this is very convenient if you use an error tracking tool or if you want to centralize your logs into one facility.
final
logLevel Level
By default the Chat client will write all messages with level Warn or Error to stdout.
final
persistenceEnabled bool
Returns True if the chatPersistenceClient is available and connected. Otherwise, returns False.
no setter
recoverStateOnReconnect bool
Whether the client should automatically refresh local state from the server when the WebSocket connection recovers.
no getter
retryPolicy RetryPolicy
The retry policy options getter
no setter
runtimeType Type
A representation of the runtime type of the object.
no setterinherited
state ClientState
This client state
getter/setter pair
wsConnectionStatus ConnectionStatus
The current status value of the _ws connection
no setter
wsConnectionStatusStream Stream<ConnectionStatus>
This notifies the connection status of the _ws connection. Listen to this to get notified when the _ws tries to reconnect.
no setter

Methods

acceptChannelInvite(String channelId, String channelType, {Message? message}) Future<AcceptInviteResponse>
Accept invitation to the channel
addChannelMembers(String channelId, String channelType, List<String> memberIds, {Message? message, bool hideHistory = false, DateTime? hideHistoryBefore}) Future<AddMembersResponse>
Add members to the channel
addDevice(String id, PushProvider pushProvider, {String? pushProviderName}) Future<EmptyResponse>
Add a device for Push Notifications.
addPollAnswer(String messageId, String pollId, {required String answerText}) Future<CastPollVoteResponse>
Adds a answer with answerText for the Poll pollId.
addUserGroupMembers(String id, List<String> memberIds, {bool? asAdmin, String? teamId}) Future<AddUserGroupMembersResponse>
Adds members to a user group.
archiveChannel({required String channelId, required String channelType}) Future<PartialUpdateMemberResponse>
Archives the channel for the current user.
banUser(String targetUserId, [Map<String, dynamic> options = const {}]) Future<EmptyResponse>
Bans a user from all channels
blockUser(String userId) Future<UserBlockResponse>
Blocks a user with the provided userId.
castPollVote(String messageId, String pollId, {required String optionId}) Future<CastPollVoteResponse>
Cast a vote for the Poll pollId.
channel(String type, {String? id, Map<String, Object?>? extraData}) Channel
Returns a channel client with the given type, id and custom data.
closeConnection() → void
Disconnects the _ws connection, without removing the user set on client.
closePersistenceConnection({bool flush = false}) Future<void>
Disconnects the chatPersistenceClient from the current user.
closePoll(String pollId) Future<UpdatePollResponse>
Marks the Poll pollId as closed.
connectAnonymousUser({bool connectWebSocket = true}) Future<OwnUser>
Connects the current user with an anonymous id, this triggers a connection to the API. It returns a Future that resolves when the connection is setup.
connectGuestUser(User user, {bool connectWebSocket = true}) Future<OwnUser>
Connects the current user as guest, this triggers a connection to the API. It returns a Future that resolves when the connection is setup.
connectUser(User user, String token, {bool connectWebSocket = true}) Future<OwnUser>
Connects the current user, this triggers a connection to the API. It returns a Future that resolves when the connection is setup. Pass connectWebSocket: false, if you want to connect to websocket at a later stage or use the client in connection-less mode
connectUserWithProvider(User user, TokenProvider tokenProvider, {bool connectWebSocket = true}) Future<OwnUser>
Connects the current user using the tokenProvider to fetch the token. It returns a Future that resolves when the connection is setup.
createChannel(String channelType, {String? channelId, Map<String, Object?>? channelData}) Future<ChannelState>
Creates a new channel
createDraft(DraftMessage draft, String channelId, String channelType) Future<CreateDraftResponse>
Creates a draft for the given channelId of type channelType.
createPoll(Poll poll) Future<CreatePollResponse>
Creates a new Poll
createPollOption(String pollId, PollOption option) Future<CreatePollOptionResponse>
Creates a new Poll Option for the Poll pollId.
createReminder(String messageId, {DateTime? remindAt}) Future<CreateReminderResponse>
Creates a reminder for the given messageId.
createUserGroup(String name, {String? id, String? description, String? teamId, List<String>? memberIds}) Future<CreateUserGroupResponse>
Creates a new user group, optionally with initial members.
deleteChannel(String channelId, String channelType) Future<EmptyResponse>
Delete this channel. Messages are permanently removed.
deleteDraft(String channelId, String channelType, {String? parentId}) Future<EmptyResponse>
Deletes a draft for the given channelId of type channelType.
deleteFile(String url, String channelId, String channelType, {CancelToken? cancelToken, Map<String, Object?>? extraData}) Future<EmptyResponse>
Delete a file from this channel
deleteImage(String url, String channelId, String channelType, {CancelToken? cancelToken, Map<String, Object?>? extraData}) Future<EmptyResponse>
Delete an image from this channel
deleteMessage(String messageId, {bool hard = false}) Future<EmptyResponse>
Deletes the given message.
deleteMessageForMe(String messageId) Future<EmptyResponse>
Deletes the given message for the current user only.
deletePoll(String pollId) Future<EmptyResponse>
Deletes the Poll by pollId.
deletePollOption(String pollId, String optionId) Future<EmptyResponse>
Deletes a Poll Option by optionId for the Poll pollId.
deleteReaction(String messageId, String reactionType) Future<EmptyResponse>
Delete a reactionType from this messageId
deleteReminder(String messageId) Future<EmptyResponse>
Deletes a reminder for the given messageId.
deleteUserGroup(String id, {String? teamId}) Future<EmptyResponse>
Deletes a user group and all its memberships.
detachedLogger(String name) Logger
Default logger for the StreamChatClient.
devToken(String userId) → Token
Get a development token
disableSlowdown(String channelId, String channelType) Future<PartialUpdateChannelResponse>
Disables slow mode
disconnectUser({bool flushChatPersistence = false}) Future<void>
Closes the _ws connection and resets the state If flushChatPersistence is true the client deletes all offline user's data.
dispose() Future<void>
Call this function to dispose the client
enableSlowdown(String channelId, String channelType, int cooldown) Future<PartialUpdateChannelResponse>
Enables slow mode
enrichUrl(String url) Future<OGAttachmentResponse>
Get OpenGraph data of the given url.
flagMessage(String messageId) Future<EmptyResponse>
Flag a message
flagUser(String userId) Future<EmptyResponse>
Flag a user
getActiveLiveLocations() Future<GetActiveLiveLocationsResponse>
Retrieves all the active live locations of the current user.
getAppSettings() Future<AppSettings>
Re-fetches the AppSettings and updates appSettings.
getDevices() Future<ListDevicesResponse>
Gets a list of user devices.
getDraft(String channelId, String channelType, {String? parentId}) Future<GetDraftResponse>
Retrieves a draft for the given channelId of type channelType.
getMessage(String messageId) Future<GetMessageResponse>
Get a message by messageId
getMessagesById(String channelId, String channelType, List<String> messageIDs) Future<GetMessagesByIdResponse>
Retrieves a list of messages by messageIDs from the given channelId of type channelType
getPoll(String pollId) Future<GetPollResponse>
Retrieves a Poll by pollId
getPollOption(String pollId, String optionId) Future<GetPollOptionResponse>
Retrieves a Poll Option by optionId for the Poll pollId.
getReactions(String messageId, {PaginationParams? pagination}) Future<QueryReactionsResponse>
Get all the reactions for a messageId
getReplies(String parentId, {PaginationParams? options}) Future<QueryRepliesResponse>
Lists all the message replies for the parentId
getThread(String messageId, {ThreadOptions options = const ThreadOptions()}) Future<GetThreadResponse>
Retrieves a thread with the given messageId.
getUnreadCount() Future<GetUnreadCountResponse>
Returns the unread count information for the current user.
getUserGroup(String id, {String? teamId}) Future<GetUserGroupResponse>
Gets a user group by ID, including its members.
handleEvent(Event event) → void
Method called to add a new event to the _eventController.
hideChannel(String channelId, String channelType, {bool clearHistory = false}) Future<EmptyResponse>
Hides the channel from queryChannels for the user until a message is added If clearHistory is set to true - all messages will be removed for the user
inviteChannelMembers(String channelId, String channelType, List<String> memberIds, {Message? message}) Future<InviteMembersResponse>
Invite members to the channel
listUserGroups({int? limit, String? idGt, DateTime? createdAtGt, String? teamId}) Future<ListUserGroupsResponse>
Lists user groups with cursor-based pagination.
markAllRead() Future<EmptyResponse>
Mark all channels for this user as read
markChannelRead(String channelId, String channelType, {String? messageId}) Future<EmptyResponse>
Mark channelId of type channelType all messages as read Optionally provide a messageId if you want to mark a particular message as read
markChannelsDelivered(Iterable<MessageDelivery> deliveries) Future<EmptyResponse>
Sends delivery receipts for the latest messages in multiple channels.
markChannelUnread(String channelId, String channelType, String messageId) Future<EmptyResponse>
Marks the channelId of type channelType as unread by a given messageId.
markChannelUnreadByTimestamp(String channelId, String channelType, DateTime timestamp) Future<EmptyResponse>
Marks the channelId of type channelType as unread by a given timestamp.
markThreadRead(String channelId, String channelType, String threadId) Future<EmptyResponse>
Mark the thread with threadId in the channel with channelId of type channelType as read.
markThreadUnread(String channelId, String channelType, String threadId) Future<EmptyResponse>
Mark the thread with threadId in the channel with channelId of type channelType as unread.
maybeDisconnect() → void

Available on StreamChatClient, provided by the MaybeReconnect extension

Optionally disconnect the client if the user is logged in and the connection is currently established.
maybeReconnect() Future<void>

Available on StreamChatClient, provided by the MaybeReconnect extension

Optionally trigger a reconnect if the user is already logged in and the client is not yet connected.
muteChannel(String channelCid, {Duration? expiration}) Future<EmptyResponse>
Mutes the channel
muteUser(String userId) Future<EmptyResponse>
Mutes a user
noSuchMethod(Invocation invocation) → dynamic
Invoked when a nonexistent method or property is accessed.
inherited
on([String? eventType, String? eventType2, String? eventType3, String? eventType4]) Stream<Event>
Stream of Event coming from _ws connection Pass an eventType as parameter in order to filter just a type of event
openConnection({bool includeUserDetailsInConnectCall = false}) Future<OwnUser>
Creates a new WebSocket connection with the current user. If includeUserDetailsInConnectCall is true it will include the current user details in the connect call.
openPersistenceConnection(User user) Future<void>
Connects the chatPersistenceClient to the given user.
partialMemberUpdate({required String channelId, required String channelType, Map<String, Object?>? set, List<String>? unset}) Future<PartialUpdateMemberResponse>
Partially updates the member of the given channel.
partialUpdateMessage(String messageId, {Map<String, Object?>? set, List<String>? unset, bool skipEnrichUrl = false}) Future<UpdateMessageResponse>
Partially update the given messageId Use set to define values to be set Use unset to define values to be unset
partialUpdatePoll(String pollId, {Map<String, Object?>? set, List<String>? unset}) Future<UpdatePollResponse>
Partially updates a Poll by pollId.
partialUpdateThread(String messageId, {Map<String, Object?>? set, List<String>? unset}) Future<UpdateThreadResponse>
Partially updates the thread with the given messageId.
partialUpdateUser(String id, {Map<String, Object?>? set, List<String>? unset}) Future<UpdateUsersResponse>
Partially update the given user with id. Use set to define values to be set. Use unset to define values to be unset.
partialUpdateUsers(List<PartialUpdateUserRequest> users) Future<UpdateUsersResponse>
Batch partial updates the users.
pauseReconnect() → void
Suspends the WebSocket's automatic reconnection without tearing down the user session.
pinChannel({required String channelId, required String channelType}) Future<PartialUpdateMemberResponse>
Pins the channel for the current user.
pinMessage(String messageId, {Object? timeoutOrExpirationDate}) Future<UpdateMessageResponse>
Pins provided message timeoutOrExpirationDate can either be a DateTime or a value in seconds to be added to DateTime.now
queryBannedUsers({required Filter filter, SortOrder<BannedUser>? sort, PaginationParams? pagination}) Future<QueryBannedUsersResponse>
Query banned users.
queryBlockedUsers() Future<BlockedUsersResponse>
Retrieves a list of all users that the current user has blocked.
queryChannel(String channelType, {bool state = true, bool watch = false, bool presence = false, String? channelId, Map<String, Object?>? channelData, PaginationParams? messagesPagination, PaginationParams? membersPagination, PaginationParams? watchersPagination}) Future<ChannelState>
Query the API, get messages, members or other channel fields Creates the channel first if not yet created
queryChannels({Filter? filter, SortOrder<ChannelState>? channelStateSort, String? predefinedFilter, Map<String, Object?>? filterValues, Map<String, Object?>? sortValues, bool state = true, bool watch = true, bool presence = false, int? memberLimit, int? messageLimit, PaginationParams paginationParams = const PaginationParams(), bool waitForConnect = true}) Stream<List<Channel>>
Requests channels with a given query.
queryChannelsOffline({Filter? filter, String? predefinedFilter, Map<String, Object?>? filterValues, Map<String, Object?>? sortValues, SortOrder<ChannelState>? channelStateSort, int? messageLimit, PaginationParams paginationParams = const PaginationParams()}) Future<List<Channel>>
Requests channels with a given query from the Persistence client.
queryChannelsOnline({Filter? filter, SortOrder<ChannelState>? sort, String? predefinedFilter, Map<String, Object?>? filterValues, Map<String, Object?>? sortValues, bool state = true, bool watch = true, bool presence = false, int? memberLimit, int? messageLimit, bool waitForConnect = true, PaginationParams paginationParams = const PaginationParams()}) Future<List<Channel>>
Requests channels with a given query from the API.
queryChannelsWithResult({Filter? filter, SortOrder<ChannelState>? channelStateSort, String? predefinedFilter, Map<String, Object?>? filterValues, Map<String, Object?>? sortValues, bool state = true, bool watch = true, bool presence = false, int? memberLimit, int? messageLimit, PaginationParams paginationParams = const PaginationParams(), bool waitForConnect = true}) Stream<QueryChannelsResult>
Requests channels with a given query, yielding a QueryChannelsResult that carries both the live channel list and the server-resolved PredefinedFilter spec (when one is associated with the query).
queryDrafts({Filter? filter, SortOrder<Draft>? sort, PaginationParams? pagination}) Future<QueryDraftsResponse>
Queries drafts for the current user.
queryMembers(String channelType, {Filter? filter, String? channelId, List<Member>? members, SortOrder<Member>? sort, PaginationParams? pagination}) Future<QueryMembersResponse>
Query channel members
queryPolls({Filter? filter, SortOrder<Poll>? sort, PaginationParams pagination = const PaginationParams()}) Future<QueryPollsResponse>
Queries Polls with the given filter and sort options.
queryPollVotes(String pollId, {Filter? filter, SortOrder<PollVote>? sort, PaginationParams pagination = const PaginationParams()}) Future<QueryPollVotesResponse>
Queries Poll Votes for the Poll pollId with the given filter and sort options.
queryReactions(String messageId, {Filter? filter, SortOrder<Reaction>? sort, PaginationParams? pagination}) Future<QueryReactionsResponse>
Queries reactions for a messageId with optional filter, sort, and pagination.
queryReminders({Filter? filter, SortOrder<MessageReminder>? sort, PaginationParams pagination = const PaginationParams()}) Future<QueryRemindersResponse>
Queries reminders for the current user.
queryThreads({Filter? filter, SortOrder<Thread>? sort, ThreadOptions options = const ThreadOptions(), PaginationParams pagination = const PaginationParams()}) Future<QueryThreadsResponse>
Queries threads with the given options and pagination params.
queryUsers({bool? presence, Filter? filter, SortOrder<User>? sort, PaginationParams? pagination}) Future<QueryUsersResponse>
Requests users with a given query.
rejectChannelInvite(String channelId, String channelType, {Message? message}) Future<RejectInviteResponse>
Reject invitation to the channel
removeChannelMembers(String channelId, String channelType, List<String> memberIds, {Message? message}) Future<RemoveMembersResponse>
Remove members from the channel
removeDevice(String id) Future<EmptyResponse>
Remove a user's device.
removeFile(String url, {CancelToken? cancelToken}) Future<EmptyResponse>
Remove a file from the Stream CDN using its url.
removeImage(String url, {CancelToken? cancelToken}) Future<EmptyResponse>
Remove an image from the Stream CDN using its url.
removePollVote(String messageId, String pollId, String voteId) Future<RemovePollVoteResponse>
Removes a vote by voteId for the Poll pollId.
removeShadowBan(String targetID, [Map<String, dynamic> options = const {}]) Future<EmptyResponse>
Removes shadow ban from a user
removeUserGroupMembers(String id, List<String> memberIds, {String? teamId}) Future<RemoveUserGroupMembersResponse>
Removes members from a user group.
resumeReconnect() → void
Re-enables the WebSocket's automatic reconnection after a previous pauseReconnect.
A message search.
searchRoles(String query, {int? limit, String? nameGt, RoleType? roleType, bool? includeGlobalRoles}) Future<SearchRolesResponse>
Searches roles by name prefix (autocomplete).
searchUserGroups(String query, {int? limit, String? nameGt, String? idGt, String? teamId}) Future<SearchUserGroupsResponse>
Searches user groups by name prefix (autocomplete).
sendAction(String channelId, String channelType, String messageId, Map<String, Object?> formData) Future<SendActionResponse>
Send action for a specific message of this channel
sendEvent(String channelId, String channelType, Event event) Future<EmptyResponse>
Send an event to a particular channel
sendFile(AttachmentFile file, String channelId, String channelType, {ProgressCallback? onSendProgress, CancelToken? cancelToken, Map<String, Object?>? extraData}) Future<SendFileResponse>
Send a file to the channelId of type channelType
sendImage(AttachmentFile image, String channelId, String channelType, {ProgressCallback? onSendProgress, CancelToken? cancelToken, Map<String, Object?>? extraData}) Future<SendImageResponse>
Send a image to the channelId of type channelType
sendMessage(Message message, String channelId, String channelType, {bool skipPush = false, bool skipEnrichUrl = false}) Future<SendMessageResponse>
Sends the message to the given channel
sendReaction(String messageId, Reaction reaction, {bool skipPush = false, bool enforceUnique = false}) Future<SendReactionResponse>
Send a reactionType for this messageId Set enforceUnique to true to remove the existing user reaction
setPushPreferences(List<PushPreferenceInput> preferences) Future<UpsertPushPreferencesResponse>
Set push preferences for the current user.
shadowBan(String targetID, [Map<String, dynamic> options = const {}]) Future<EmptyResponse>
Shadow bans a user
showChannel(String channelId, String channelType) Future<EmptyResponse>
Removes the hidden status for the channel
stopChannelWatching(String channelId, String channelType) Future<EmptyResponse>
Stop watching the channel
stopLiveLocation({required String messageId, String? createdByDeviceId}) Future<Location>
Expire an existing live location created by the current user.
sync({List<String>? cids, DateTime? lastSyncAt}) Future<void>
Get the events missed while offline to sync the offline storage Will automatically fetch cids and lastSyncedAt if persistenceEnabled
toString() String
A string representation of this object.
inherited
translateMessage(String messageId, String language) Future<TranslateMessageResponse>
Translates the messageId in provided language
truncateChannel(String channelId, String channelType, {Message? message, bool? skipPush, DateTime? truncatedAt}) Future<EmptyResponse>
Removes all messages from the channel up to truncatedAt or now if truncatedAt is not provided. If skipPush is true, no push notification will be sent. Message is the system message that will be sent to the channel.
unarchiveChannel({required String channelId, required String channelType}) Future<PartialUpdateMemberResponse>
Unarchives the channel for the current user.
unbanUser(String targetUserId, [Map<String, dynamic> options = const {}]) Future<EmptyResponse>
Remove global ban for a user
unblockUser(String userId) Future<EmptyResponse>
Unblocks a previously blocked user with the provided userId.
unflagMessage(String messageId) Future<EmptyResponse>
Unflag a message.
unflagUser(String userId) Future<EmptyResponse>
Unflag a user.
unmuteChannel(String channelCid) Future<EmptyResponse>
Unmutes the channel
unmuteUser(String userId) Future<EmptyResponse>
Unmutes a user
unpinChannel({required String channelId, required String channelType}) Future<PartialUpdateMemberResponse>
Unpins the channel for the current user.
unpinMessage(String messageId) Future<UpdateMessageResponse>
Unpins provided message
updateChannel(String channelId, String channelType, Map<String, Object?> data, {Message? message}) Future<UpdateChannelResponse>
Replaces the channelId of type ChannelType data with data.
updateChannelPartial(String channelId, String channelType, {Map<String, Object?>? set, List<String>? unset}) Future<PartialUpdateChannelResponse>
Partial update for the channelId of type ChannelType. Sets the data provided in set, and removes the attributes given in unset.
updateLiveLocation({required String messageId, String? createdByDeviceId, LocationCoordinates? location, DateTime? endAt}) Future<Location>
Updates an existing live location created by the current user.
updateMessage(Message message, {bool skipPush = false, bool skipEnrichUrl = false}) Future<UpdateMessageResponse>
Update the given message
updatePoll(Poll poll) Future<UpdatePollResponse>
Updates a Poll
updatePollOption(String pollId, PollOption option) Future<UpdatePollOptionResponse>
Updates a Poll Option for the Poll pollId.
updateReminder(String messageId, {DateTime? remindAt}) Future<UpdateReminderResponse>
Updates a reminder for the given messageId.
updateSystemEnvironment(SystemEnvironment environment) → void
Updates the system environment information used by the client.
updateUser(User user) Future<UpdateUsersResponse>
Update or Create the given user object.
updateUserGroup(String id, {String? name, String? description, String? teamId}) Future<UpdateUserGroupResponse>
Updates a user group's name and/or description.
updateUsers(List<User> users) Future<UpdateUsersResponse>
Batch update a list of users
uploadFile(AttachmentFile file, {ProgressCallback? onUploadProgress, CancelToken? cancelToken}) Future<SendImageResponse>
Upload a file to the Stream CDN
uploadImage(AttachmentFile image, {ProgressCallback? onUploadProgress, CancelToken? cancelToken}) Future<SendImageResponse>
Upload an image to the Stream CDN
watchChannel(String channelType, {String? channelId, Map<String, Object?>? channelData}) Future<ChannelState>
watches the provided channel Creates first if not yet created

Operators

operator ==(Object other) bool
The equality operator.
inherited

Static Properties

additionalHeaders Map<String, Object?>
Additional headers for all requests
getter/setter pair
defaultUserAgent String
Default user agent for all requests
getter/setter pair

Static Methods

defaultLogHandler(LogRecord record) → void
Default log handler function for the StreamChatClient logger.

Constants

packageVersion → const String
The current package version