/ SDKs / Flutter
SDKs
Chat SDKs Flutter v4
Chat SDKs Flutter
Chat SDKs
Flutter
Version 4

Local caching

Copy link

Local caching enables Sendbird Chat SDK for Flutter to locally cache and retrieve group channel and message data. Its benefits include reducing refresh time and allowing a client app to create a channel list or a chat view that can work online as well as offline.

You can enable local caching when initializing the Chat SDK by setting the optional parameter useCollectionCaching to true. To learn more, see Initialize the Chat SDK page.

Local caching relies on the GroupChannelCollection and MessageCollection classes, which are used to build a channel list view and a chat view, respectively. Collections are designed to react to events that can cause change in a channel list or chat view. An event controller in the SDK oversees such events and passes them to a relevant collection. For example, if a new group channel is created while the current user is looking at a chat view, the current view won't be affected by this event.

Note: You can still use these collections without the local caching functionality when building your app.


Functionalities by topic

Copy link

The following is a list of functionalities our Chat SDK supports.

Using group channel collection

Copy link
FunctionalityDescriptionOpen channelGroup channel

Group channel collection

Keeps the client app's channel list synced with the Sendbird server.

Using message collection

Copy link
FunctionalityDescriptionOpen channelGroup channel

Message collection

Keeps the client app's chat view synced with the Sendbird server.


GroupChannelCollection

Copy link

You can use GroupChannelCollection to create a channel list view that stays up-to-date on all events related to the channel view. When the GroupChannelCollection instance is created, the group channel data are fetched from the Sendbird server. Also, GroupChannelCollectionHandler lets you set the event listeners that can subscribe to channel-related events when creating the collection.

As for pagination, hasMore checks if there are more group channels to load whenever a user hits the bottom of the channel list. If so, loadMore() retrieves and sorted channels based on the values in GroupChannelListQuery from the local cache and the Sendbird server to display on the list.

To learn more about the collection and how to create a channel list view with it, see Group channel collection.

// First, create a GroupChannelListQuery instance.
final query = GroupChannelListQuery()
  ..order = GroupChannelListQueryOrder.chronological;
  // Acceptable values are chronological, latestLastMessage(default), channelNameAlphabetical and metadataValueAlphabetical.
  // You can add other params setters.

// Second, create MyGroupChannelCollectionHandler instance.
final handler = MyGroupChannelCollectionHandler();
class MyGroupChannelCollectionHandler extends GroupChannelCollectionHandler {
  @override
  void onChannelsAdded(ChannelContext context, List<GroupChannel> channels) {
    // Update widgets with collection.channelList.
  }
  @override
  void onChannelsUpdated(ChannelContext context, List<GroupChannel> channels) {
    // Update widgets with collection.channelList.
  }
  @override
  void onChannelsDeleted(ChannelContext context, List<String> deletedChannelUrls) {
    // Update widgets with collection.channelList.
  }
}

// Create a GroupChannelCollection instance.
final collection = GroupChannelCollection(query: query, handler: handler);

// Load channels.
try {
  // Check whether there are more channels to load before calling loadMore().
  if (collection.hasMore) {
      await collection.loadMore();
  }
} catch (e) {
  // Handle error.
}

// Clear the collection.
collection.dispose();

MessageCollection

Copy link

You can use MessageCollection to create a chat view that includes all up-to-date data.

As for pagination, hasNext checks if there are more messages to load whenever a user hits the bottom of the chat view. If so, the loadNext() method retrieves messages from the local cache to display in the view. hasPrevious and loadPrevious() work the same way when the scroll reaches the top of the chat view.

To learn more about the collection and how to create a chat view with it, see Message collection.

final collection = MessageCollection(
  channel: channel,
  params: MessageListParams(),
  handler: MyMessageCollectionHandler(),
  startingPoint: SendbirdChat.maxInt,
);

class MyMessageCollectionHandler extends MessageCollectionHandler {
  @override
  void onMessagesAdded(MessageContext context, GroupChannel channel, List<BaseMessage> messages) {
    // Update widgets with collection.messageList.
  }
  @override
  void onMessagesUpdated(MessageContext context, GroupChannel channel, List<BaseMessage> messages) {
    // Update widgets with collection.messageList.
  }
  @override
  void onMessagesDeleted(MessageContext context, GroupChannel channel, List<BaseMessage> messages) {
    // Update widgets with collection.messageList.
  }
  @override
  void onChannelUpdated(ChannelContext context, GroupChannel channel) {
    // Update widgets with collection.messageList.
  }
  @override
  void onChannelDeleted(ChannelContext context, String deletedChannelUrl) {
    // Back to the previous page.
  }
  @override
  void onHugeGapDetected() {
    // The Chat SDK detects that more than 300 messages are missing.
    collection.dispose();        // Dispose the collection.
    createMessageCollection();   // Create a new message collection object.
    // An additional implementation is required for initialization.
  }
}

// Initialize messages from startingPoint.
try {
  // Initialize messages from the startingPoint.
  await collection.initialize();
  // Messages are retrieved through API calls from the Sendbird server.
} catch (e) {
  // Handle error.
}

// Load previous messages.
try {
  // Load the previous messages
  // when the scroll reaches the first message in the chat view.
  if (collection.hasPrevious) {
      await collection.loadPrevious();
  }
} catch (e) {
  // Handle error.
}

// Load the next set of messages.
try {
  // Load the next set of messages
  // when the scroll reaches the last message in the chat view.
  if (collection.hasNext) {
      await collection.loadNext();
  }
} catch (e) {
  // Handle error.
}

// Clear the collection.
collection.dispose();

Gap and synchronization

Copy link

A gap is created when messages or channels that exist on the Sendbird server are missing from the local cache. Such discrepancy occurs when a client app isn't able to properly load new events due to connectivity issues. To prevent such a gap, the Chat SDK constantly communicates with the Sendbird server and fetches data through synchronization, pulling a chunk of messages before and after startingPoint.

Such gap can significantly widen if a user has been offline for a long time. If more than 300 messages are missing in the local cache compared to the Sendbird server, Sendbird Chat SDK classifies this as a huge gap and onHugeGapDetected() is called. In case of a huge gap, it is more effective to discard the existing message collection and create a new one. On the other hand, a relatively small gap created when the SDK was offline can be filled in through changelog sync.


Resend failed messages

Copy link

A message is normally sent through the WebSocket connection which means the connection must be secured for messages to be sent successfully. In the case of a lost connection, the local caching feature allows you to keep unsent messages in the cache temporarily. Then, you can implement the code below to manually resend messages that are in the local cache.

if (message.sendingStatus == SendingStatus.failed) {
  if (message is UserMessage) {
    // Resend a user message.
    messageCollection.channel.resendUserMessage(message);
  } else if (message is FileMessage) {
    // Resend a file message.
    messageCollection.channel.resendFileMessage(message);
  }
}

Database management

Copy link

The max size of database is 256 MB. When this limit is reached, the SDK clears 128 MB(half) of the cached messages.


Other methods

Copy link

The following is a list of methods and params that allows you to leverage the local caching functionalities.

MethodDescription

SendbirdChat.getCachedDataSize()

Retrieves the size of the stored data in the local cache.

SendbirdChat.clearCachedData()

Erases the entire data in the local cache.

SendbirdChat.clearCachedMessages()

Clears messages from the local caches by specifying the channel URL of those messages.

ParamsDescription

UserMessage.messageCreateParams

Draws pending user messages in the chat view. Can be passed to the channel.sendUserMessage(params) method.

FileMessage.messageCreateParams

Draws pending file messages in the chat view. Can be passed to the channel.sendFileMessage(params) method.

final cachedDataSize = await SendbirdChat.getCachedDataSize();
await SendbirdChat.clearCachedData();
await SendbirdChat.clearCachedMessages('CHANNEL_URL');

// These should be used for displaying pending messages in the chat view.
final userMesageParams = userMessage.messageCreateParams;
final fileMessageParams = fileMessage.messageCreateParams;