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.new(String apiKey, {Level logLevel = Level.WARNING, LogHandlerFunction logHandlerFunction = StreamChatClient.defaultLogHandler, RetryPolicy? retryPolicy, String? baseURL, String? baseWsUrl, Duration connectTimeout = const Duration(seconds: 6), Duration receiveTimeout = const Duration(seconds: 6), StreamChatApi? chatApi, WebSocket? ws, AttachmentFileUploaderProvider attachmentFileUploaderProvider = StreamAttachmentFileUploader.new, Iterable<
Interceptor> ? chatApiInterceptors, HttpClientAdapter? httpClientAdapter}) - 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 typesno 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.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, returnsFalse
.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
connectionno 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}) → 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 PollpollId
. -
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 PollpollId
. -
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. -
createCall(
{required String callId, required String callType, required String channelType, required String channelId}) → Future< CreateCallPayload> - Creates a new call.
-
createChannel(
String channelType, {String? channelId, Map< String, Object?> ? channelData}) → Future<ChannelState> - Creates a new channel
-
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
. -
deleteChannel(
String channelId, String channelType) → Future< EmptyResponse> - Delete this channel. Messages are permanently removed.
-
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
-
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 PollpollId
. -
deleteReaction(
String messageId, String reactionType) → Future< EmptyResponse> -
Delete a
reactionType
from thismessageId
-
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 IfflushChatPersistence
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
-
getCallToken(
String callId) → Future< CallTokenPayload> -
Returns a token associated with the
callId
. -
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 givenchannelId
of typechannelType
-
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 PollpollId
. -
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
. -
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 typechannelType
all messages as read Optionally provide amessageId
if you want to mark a particular message as read -
markChannelUnread(
String channelId, String channelType, String messageId) → Future< EmptyResponse> -
Mark
channelId
of typechannelType
all messages as read Optionally provide amessageId
if you want to mark a particular message as read -
markThreadRead(
String channelId, String channelType, String threadId) → Future< EmptyResponse> -
Mark the thread with
threadId
in the channel withchannelId
of typechannelType
as read. -
markThreadUnread(
String channelId, String channelType, String threadId) → Future< EmptyResponse> -
Mark the thread with
threadId
in the channel withchannelId
of typechannelType
as unread. -
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
. -
partialUpdateMessage(
String messageId, {Map< String, Object?> ? set, List<String> ? unset, bool skipEnrichUrl = false}) → Future<UpdateMessageResponse> -
Partially update the given
messageId
Useset
to define values to be set Useunset
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
. Useset
to define values to be set. Useunset
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.
-
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, List< SortOption< ? channelStateSort, bool state = true, bool watch = true, bool presence = false, int? memberLimit, int? messageLimit, PaginationParams paginationParams = const PaginationParams(), bool waitForConnect = true}) → Stream<ChannelState> >List< Channel> > - Requests channels with a given query.
-
queryChannelsOffline(
{Filter? filter, List< SortOption< ? channelStateSort, PaginationParams paginationParams = const PaginationParams()}) → Future<ChannelState> >List< Channel> > - Requests channels with a given query from the Persistence client.
-
queryChannelsOnline(
{Filter? filter, List< SortOption> ? 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
-
queryPolls(
{Filter? filter, List< SortOption> ? sort, PaginationParams pagination = const PaginationParams()}) → Future<QueryPollsResponse> -
Queries Polls with the given
filter
andsort
options. -
queryPollVotes(
String pollId, {Filter? filter, List< SortOption> ? sort, PaginationParams pagination = const PaginationParams()}) → Future<QueryPollVotesResponse> -
Queries Poll Votes for the Poll
pollId
with the givenfilter
andsort
options. -
queryThreads(
{ThreadOptions options = const ThreadOptions(), PaginationParams pagination = const PaginationParams()}) → Future< QueryThreadsResponse> -
Queries threads with the given
options
andpagination
params. -
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.
-
removePollVote(
String messageId, String pollId, String voteId) → Future< RemovePollVoteResponse> -
Removes a vote by
voteId
for the PollpollId
. -
removeShadowBan(
String targetID, [Map< String, dynamic> options = const {}]) → Future<EmptyResponse> - Removes shadow ban from a user
-
search(
Filter filter, {String? query, List< SortOption> ? sort, PaginationParams? paginationParams, Filter? messageFilters}) → Future<SearchMessagesResponse> - 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, Map< String, Object?> ? extraData}) → Future<SendFileResponse> -
Send a
file
to thechannelId
of typechannelType
-
sendImage(
AttachmentFile image, String channelId, String channelType, {ProgressCallback? onSendProgress, CancelToken? cancelToken, Map< String, Object?> ? extraData}) → Future<SendImageResponse> -
Send a
image
to thechannelId
of typechannelType
-
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, String reactionType, {int score = 1, Map< String, Object?> extraData = const {}, bool enforceUnique = false}) → Future<SendReactionResponse> -
Send a
reactionType
for thismessageId
SetenforceUnique
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
andlastSyncedAt
if persistenceEnabled -
toString(
) → String -
A string representation of this object.
inherited
-
translateMessage(
String messageId, String language) → Future< TranslateMessageResponse> -
Translates the
messageId
in providedlanguage
-
truncateChannel(
String channelId, String channelType, {Message? message, bool? skipPush, DateTime? truncatedAt}) → Future< EmptyResponse> -
Removes all messages from the channel up to
truncatedAt
or now iftruncatedAt
is not provided. IfskipPush
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
-
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 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 typeChannelType
data withdata
. -
updateChannelPartial(
String channelId, String channelType, {Map< String, Object?> ? set, List<String> ? unset}) → Future<PartialUpdateChannelResponse> -
Partial update for the
channelId
of typeChannelType
. Sets the data provided inset
, and removes the attributes given inunset
. -
updateMessage(
Message message, {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
. -
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.
-
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?> -
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