Contentstack Delivery Dart SDK
Overview
Warning Contentstack has deprecated the Dart Delivery SDK for new projects. Existing apps can keep using it. For new Dart or Flutter projects, call the Content Delivery API directly with an HTTP client.
This reference covers the public API of the contentstack package for Dart and Flutter, with one page per class. Use it to look up parameters, return types, validation behavior, and worked examples for every object you reach from contentstack.Stack.
Before you begin This reference assumes you have installed and initialized the SDK. If you have not, complete the Get Started with Dart SDK guide first. To add the SDK, list contentstack: ^1.0.3 under dependencies in pubspec.yaml, then run dart pub get, or flutter pub get in a Flutter app. This SDK requires a Dart SDK from 2.12.0 up to, but not including, 4.0.0, which includes Dart 3. This reference documents version 1.0.3, and the changelog lists behavior changes between releases.
Minimum Working Example
The snippet below creates a stack, fetches one entry, and prints its title, or the error code when the API rejects the request.
import 'package:contentstack/contentstack.dart' as contentstack;
Future<void> main() async {
final stack = contentstack.Stack('<API_KEY>', '<DELIVERY_TOKEN>', '<ENVIRONMENT>');
final entry = stack.contentType('<CONTENT_TYPE_UID>').entry(entryUid: '<ENTRY_UID>');
try {
final response = await entry.fetch();
if (response is Map && response.containsKey('error_code')) {
// The API rejected the request
print('Request failed: ${response['error_code']} ${response['error_message']}');
} else {
print(response['entry']['title']);
}
} catch (e) {
// Thrown for a missing UID, a non-JSON response, a network failure or a 30-second timeout
print('Request did not complete: $e');
}
}SDK Structure
The SDK uses a builder pattern. Stack takes your credentials. Each factory call on it returns an object for a narrower scope, such as a content type, an entry, a query, an asset, or an image URL. Setters on that object store a value and return void, so you chain several of them on one object with the Dart cascade operator ... Every chain starts at the Stack.
A terminal call sends the request and returns a Future, which you await. The three groups of terminal calls below each send one request:
- fetch on Entry, Asset, and ContentType, for one item
- find on Query, AssetQuery, and ContentTypeQuery, for one page of a list
- sync, paginationToken, syncToken, getContentTypes, and globalField on Stack
Unlike these terminal calls, getUrl on ImageTransformation and getQueryUrl on Query build their output in the app and send no request.
Because a setter only stores its value, an invalid value fails on the terminal call, not where you passed it. When the API rejects the request, the terminal call returns the error body as its result instead of throwing. The Validation section of each method page states which case applies.
Class Overview
| Class | Role | Accessed via |
|---|---|---|
| Stack | One stack, environment, region, and branch, and the start of every chain. | contentstack.Stack(...) |
| ContentType | One content type of the stack and its schema. | stack.contentType(uid) |
| ContentTypeQuery | A request for the content types of the stack. | contentType.query() |
| Entry | One published entry of a content type. | contentType.entry(entryUid: uid) |
| Query | A filtered request for the published entries of one content type. | entry.query() |
| Asset | One published asset, such as an image or a PDF. | stack.asset(uid) |
| AssetQuery | A request for the published assets of the stack. | stack.assetQuery() |
| ImageTransformation | An image URL and the Image Delivery API parameters to add to it. | stack.imageTransform(url) |
| Error | The details of a Content Delivery API error, built from the map a request returns. | contentstack.Error.fromJson(map) |
Task Index
| Task | Start here | Class |
|---|---|---|
| Fetch one entry by UID | fetch | Entry |
| Filter entries by a field value | where | Query |
| Page through the entries of a content type | skip | Query |
| Return referenced entries in full | includeReference | Entry |
| Read an entry in another locale | locale | Entry |
| Read the schema of a content type | fetch | ContentType |
| Fetch one asset by UID | fetch | Asset |
| List the published assets in the stack | find | AssetQuery |
| Sync all published content, then only what changed | sync | Stack |
| Build a resized or converted image URL | getUrl | ImageTransformation |
| Read an API error as typed fields | fromJson | Error |
| Set the region, host, or branch | stack | Stack |
Key Usage Patterns
Each example below is a complete Dart program with its own imports and stack. The Minimum Working Example above shows the full error check, so these examples await each call and print the result.
Filter entries by a field and resolve a reference
import 'package:contentstack/contentstack.dart' as contentstack;
import 'package:contentstack/src/enums/operations.dart';
import 'package:contentstack/src/enums/operations_type.dart';
Future<void> main() async {
final stack = contentstack.Stack('<API_KEY>', '<DELIVERY_TOKEN>', '<ENVIRONMENT>');
// The setters store values. find sends the request.
final query = stack.contentType('<CONTENT_TYPE_UID>').entry().query()
..where('category', QueryOperation(QueryOperationType.Equals, 'news'))
..includeReference('author')
..orderByDescending('updated_at')
..limit(10);
final response = await query.find();
for (final entry in response['entries']) {
print(entry['title']);
print(entry['author']);
}
}Page through every entry of a content type
The SDK sends one request per find call and does not request further pages. The loop below builds a new query for each page with skip and limit, and stops at the total that the include_count parameter adds.
import 'package:contentstack/contentstack.dart' as contentstack;
Future<void> main() async {
final stack = contentstack.Stack('<API_KEY>', '<DELIVERY_TOKEN>', '<ENVIRONMENT>');
const pageSize = 100;
var skip = 0;
var total = 0;
do {
final query = stack.contentType('<CONTENT_TYPE_UID>').entry().query()
..limit(pageSize)
..skip(skip)
..param('include_count', 'true');
final response = await query.find();
total = response['count'];
for (final entry in response['entries']) {
print(entry['title']);
}
skip += pageSize;
} while (skip < total);
}Sync all published content, then only what changed
import 'package:contentstack/contentstack.dart' as contentstack;
Future<void> main() async {
final stack = contentstack.Stack('<API_KEY>', '<DELIVERY_TOKEN>', '<ENVIRONMENT>');
var response = await stack.sync();
final items = <dynamic>[...response['items']];
// Follow each pagination_token until a response carries a sync_token
while (response['pagination_token'] != null) {
response = await stack.paginationToken(response['pagination_token']);
items.addAll(response['items']);
}
print('published items: ${items.length}');
// Store the sync_token, then pass it on a later run to receive only the changes
final changes = await stack.syncToken(response['sync_token']);
print('changed since the first sync: ${changes['items'].length}');
}Build a resized WebP URL for an image asset
import 'package:contentstack/contentstack.dart' as contentstack;
import 'package:contentstack/src/image/format.dart';
Future<void> main() async {
final stack = contentstack.Stack('<API_KEY>', '<DELIVERY_TOKEN>', '<ENVIRONMENT>');
final response = await stack.asset('<ASSET_UID>').fetch();
// imageTransform and the setters store parameters. getUrl builds the string and makes no request.
final transform = stack.imageTransform(response['asset']['url'])
..resize(width: 320)
..convert(Format.Webp)
..quality(80);
print(transform.getUrl());
}Build typed entry models from a query result
A typed find throws TypeError, so the program below calls find without type arguments and builds each EntryModel from the map. A typed fetch returns an EntryModel directly.
import 'package:contentstack/contentstack.dart' as contentstack;
Future<void> main() async {
final stack = contentstack.Stack('<API_KEY>', '<DELIVERY_TOKEN>', '<ENVIRONMENT>');
final response = await stack.contentType('<CONTENT_TYPE_UID>').entry().query().find();
final models = [
for (final entry in response['entries']) contentstack.EntryModel.fromJson(entry),
];
for (final model in models) {
print('${model.uid}: ${model.title}');
}
// On an API rejection, every field of the model is null
final one = await stack
.contentType('<CONTENT_TYPE_UID>')
.entry(entryUid: '<ENTRY_UID>')
.fetch<contentstack.EntryModel, void>();
print(one?.title);
}Connect to a stack in another region on a branch
import 'package:contentstack/contentstack.dart' as contentstack;
Future<void> main() async {
final stack = contentstack.Stack(
'<API_KEY>',
'<DELIVERY_TOKEN>',
'<ENVIRONMENT>',
region: contentstack.Region.eu,
branch: '<BRANCH>',
);
print('host: ${stack.host}');
final response = await stack.contentType('<CONTENT_TYPE_UID>').entry(entryUid: '<ENTRY_UID>').fetch();
print(response['entry']['title']);
}SDK-Wide Notes
| Concern | Behavior | Default when unset |
|---|---|---|
| Authentication | contentstack.Stack takes the API key, delivery token, and environment as its first three arguments, and sends them as the api_key, access_token, and environment headers on every request. No other method takes credentials. | Not applicable. The constructor throws ArgumentError only when a value has no letter, digit, or underscore, so a wrong value fails at the first request with an API rejection. |
| API rejections | A request method returns the API error body as its result instead of throwing, a Map with error_code, error_message, and, for some errors, errors. Check for error_code before you read the result, and pass the map to fromJson when you want an Error. | Not applicable. The SDK never creates an Error itself. |
| Exceptions | A request throws TimeoutException after 30 seconds, Exception or FormatException when the body is not JSON, and any network exception of the http package unchanged, for example SocketException. A bad argument throws before any request, for example ArgumentError from the Stack constructor or Exception from fetch without a UID. | Not applicable. Wrap each terminal call in try and catch. |
| Response shape | Without type arguments, every request method returns the decoded JSON body as a Map, for example {'entry': {...}} or {'entries': [...]}. | The decoded Map. |
| Typed results | fetch<contentstack.EntryModel, void>() and fetch<contentstack.AssetModel, void>() return a model, and <contentstack.SyncResult, void> does the same for the sync methods. Known issue: On an API rejection a typed call returns a model with every field null, and a typed find always throws TypeError, as Entry fetch and Query find describe. | No model. Call without type arguments to read the Map. |
| Imports | Import the SDK with as contentstack, because its Error class shares its name with Error in dart:core. Import a type that the main library does not export, such as AssetQuery, QueryOperation, or Format, from its src/ path, as each class page shows. | Not applicable. |
| Regions and endpoints | Pass region: to the Stack constructor with Region.us, Region.eu, Region.azure_na, or Region.gcp_na to set the delivery host. Region has no AU, Azure EU, or GCP EU value, so for those regions keep Region.us and pass the delivery host of your region as host:. | Region.us, with the host cdn.contentstack.io. |
| Branches | Pass branch: to the Stack constructor. The SDK sends it as the branch header on every request from the stack. | null, so the SDK sends no branch header. |
| Rate limiting and retry | This SDK does not auto-retry on 429, so implement backoff in your calling code. Each request makes one attempt, also on a timeout. | No retry. |
| Timeouts | Each Content Delivery API request times out after 30 seconds and throws TimeoutException from dart:async. No argument or method changes the timeout. | 30 seconds. |
| Custom HTTP client | The Stack constructor takes a client: from the http package. Known issue: The SDK sends its Content Delivery API requests without that client, so a proxy, logging, or mock client has no effect on them. Wrap your calls in runWithClient from the http package instead, as the stack page describes. | null. The SDK calls the http package directly. |
Warning This SDK requires a delivery token, which the stack sends as the access_token header. The constructor does not check the token against the API, so a management token in its place passes the constructor and fails at the first request, which returns the API rejection as its result. Pass a management token only as the authorization key of the livePreview map. Refer to Content Delivery API Errors for the full error code list.
SDK Limitations
| Capability | Supported | Notes / Alternative |
|---|---|---|
| Catch an API rejection as an exception | No | Check the result for error_code, as the Minimum Working Example above does, or throw contentstack.Error.fromJson(response) yourself, as the Error page shows. |
| Retry a rate-limited or failed request automatically | No | Check the result for error_code and send the request again after a delay in your code. |
| Change the request timeout | No | None. Every Content Delivery API request times out after 30 seconds. |
| Read every page of a list in one call | No | Loop with skip and limit, and pass each pagination_token to paginationToken, as in Key Usage Patterns above. |
| Typed lists from find | No | Call find() without type arguments and build each model with EntryModel.fromJson or AssetModel.fromJson, as in Key Usage Patterns above. |