Skip to main content

Getting Started with Momento Topics in Dart

If you need to get going quickly with Dart and Momento Topics, this page contains the basic API calls you'll need. Check the Dart SDK examples for complete, working code samples.

Install the Momento SDK

The Momento Dart SDK is available on pub.dev as momento.

To install in your Dart program, use:

dart pub add momento

To install in your Flutter program, use:

flutter pub add momento

Get your Momento API key

You'll need a Momento API key. You can get one from the Momento Web Console. Once you have your token, store it in an environment variable so that the Momento client can consume it:

export MOMENTO_API_KEY=<your api key here>

Note: it is best practice to put the API key into something like AWS Secret Manager or GCP Secret Manager instead of an environment variable for enhanced security, but we are using one here for demo purposes.

Set up a TopicClient

This code creates the TopicClient that you will use to interact with your pub/sub topic.

try {
final topicClient = TopicClient(
CredentialProvider.fromEnvironmentVariable("MOMENTO_API_KEY"),
TopicClientConfigurations.latest());
} catch (e) {
print("Unable to create topic client: $e");
exit(1);
}

Publish a message to a topic

This is an example of publishing a message to a topic called "topic", then catching the return value to check if the publish was successful.

final result = await topicClient.publish("cache", "topic", "hello message!");
switch (result) {
case TopicPublishSuccess():
print("Successful publish!");
case TopicPublishError():
print("Publish error: ${result.errorCode} ${result.message}");
}

Subscribe to a topic

This is an example of subscribing to a topic called "topic", then catching the return value to check if it was successful. If a subscription was received, an await for loop is used to asynchronously receive and print the messages that are published to this topic.

final subscription = await topicClient.subscribe("test-cache", "test-topic");
final messageStream = switch (subscription) {
TopicSubscription() => subscription.stream,
TopicSubscribeError() => throw Exception(
"Subscribe error: ${subscription.errorCode} ${subscription.message}"),
};

// cancel subscription 5 seconds from now
Timer(const Duration(seconds: 5), () {
print("Cancelling subscription!");
subscription.unsubscribe();
});

try {
await for (final msg in messageStream) {
switch (msg) {
case TopicSubscriptionItemBinary():
print("Binary value: ${msg.value}");
case TopicSubscriptionItemText():
print("String value: ${msg.value}");
}
}
} catch (e) {
print("Runtime type: ${e.runtimeType}");
print("Error with await for loop: $e");
}

Running the code

You can find complete, working examples in the Dart SDK GitHub repo examples directory.

info

Beyond these basic API calls check out the API reference page for more information on the full assortment of Momento API calls.