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");

Constructors

StreamChatClient(String apiKey, {Level logLevel = Level.WARNING, LogHandlerFunction? logHandlerFunction, RetryPolicy? retryPolicy, @Deprecated(''' Location is now deprecated in favor of the new edge server. Will be removed in v4.0.0. Read more here: https://getstream.io/blog/chat-edge-infrastructure ''') Location? location, String? baseURL, Duration connectTimeout = const Duration(seconds: 6), Duration receiveTimeout = const Duration(seconds: 6), StreamChatApi? chatApi, WebSocket? ws, AttachmentFileUploader? attachmentFileUploader})
Create a client instance with default options. You should only create the client once and re-use it across your application.

Properties

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
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.
getter/setter pair
logLevel Level
By default the Chat client will write all messages with level Warn or Error to stdout.
final
persistenceEnabled bool
Whether the chat persistence is available or not
no setter
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}) Future<AddMembersResponse>
Add members to the channel
addDevice(String id, PushProvider pushProvider) Future<EmptyResponse>
Add a device for Push Notifications.
banUser(String targetUserId, [Map<String, dynamic> options = const {}]) Future<EmptyResponse>
Bans a user from all channels
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.
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
deleteChannel(String channelId, String channelType) Future<EmptyResponse>
Delete this channel. Messages are permanently removed.
deleteFile(String url, String channelId, String channelType, {CancelToken? cancelToken}) Future<EmptyResponse>
Delete a file from this channel
deleteImage(String url, String channelId, String channelType, {CancelToken? cancelToken}) Future<EmptyResponse>
Delete an image from this channel
deleteMessage(String messageId, {bool? hard}) Future<EmptyResponse>
Deletes the given message
deleteReaction(String messageId, String reactionType) Future<EmptyResponse>
Delete a reactionType from this messageId
detachedLogger(String name) Logger
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
getDevices() Future<ListDevicesResponse>
Gets a list of user devices.
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
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
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
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
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.
partialUpdateMessage(String messageId, {Map<String, Object?>? set, List<String>? unset}) Future<UpdateMessageResponse>
Partially update the given messageId Use set to define values to be set Use unset to define values to be unset
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.
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, List<SortOption>? sort, PaginationParams? pagination}) Future<QueryBannedUsersResponse>
Query banned users.
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, List<SortOption<ChannelModel>>? sort, 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, List<SortOption<ChannelModel>>? sort, PaginationParams paginationParams = const PaginationParams()}) Future<List<Channel>>
Requests channels with a given query from the Persistence client.
queryChannelsOnline({Filter? filter, List<SortOption<ChannelModel>>? sort, 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.
queryMembers(String channelType, {Filter? filter, String? channelId, List<Member>? members, List<SortOption>? sort, PaginationParams? pagination}) Future<QueryMembersResponse>
Query channel members
queryUsers({bool? presence, Filter? filter, List<SortOption>? 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.
removeShadowBan(String targetID, [Map<String, dynamic> options = const {}]) Future<EmptyResponse>
Removes shadow ban from a user
A message search.
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}) Future<SendFileResponse>
Send a file to the channelId of type channelType
sendImage(AttachmentFile image, String channelId, String channelType, {ProgressCallback? onSendProgress, CancelToken? cancelToken}) Future<SendImageResponse>
Send a image to the channelId of type channelType
sendMessage(Message message, String channelId, String channelType, {bool skipPush = false}) Future<SendMessageResponse>
Sends the message to the given channel
sendReaction(String messageId, String reactionType, {int score = 1, Map<String, Object?> extraData = const {}, bool enforceUnique = false}) Future<SendReactionResponse>
Send a reactionType for this messageId Set enforceUnique to true to remove the existing user reaction
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
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.
unbanUser(String targetUserId, [Map<String, dynamic> options = const {}]) Future<EmptyResponse>
Remove global ban for a user
unflagMessage(String messageId) Future<EmptyResponse>
Unflag a message
unflagUser(String userId) Future<EmptyResponse>
Unflag a message
unmuteChannel(String channelCid) Future<EmptyResponse>
Unmutes the channel
unmuteUser(String userId) Future<EmptyResponse>
Unmutes a 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.
updateMessage(Message message) Future<UpdateMessageResponse>
Update the given message
updateUser(User user) Future<UpdateUsersResponse>
Update or Create the given user object.
updateUsers(List<User> users) Future<UpdateUsersResponse>
Batch update a list of users
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?>
Additionals headers for all requests
getter/setter pair
defaultUserAgent String
Default user agent for all requests
getter/setter pair