Stack

View as Markdown

Stack

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.

A stack holds the content and assets of one project. Stack is the entry point to this SDK. Create it once with your credentials, then call its methods to reach every other class. Use this class to

  • connect to one stack, environment, region and branch
  • open content types, assets and image transformations
  • read the content types and global fields of the stack
  • synchronize published content through the Sync API

contentstack.Stack(apiKey, deliveryToken, environment, {...}) takes the arguments below. The first three are positional. Pass the others by name, for example branch: '<BRANCH>'.

NameTypeDescription
apiKeyStringAPI key of the stack. Required.
deliveryTokenStringDelivery token of the environment. Required.
environmentStringEnvironment to read published content from. Required.
apiVersionStringAPI version segment of every request path. Defaults to 'v3'.
regionRegionRegion of the stack. Defaults to Region.us.
branchString?Branch to read content from. Defaults to null.
hostString?Delivery host. Defaults to 'cdn.contentstack.io'.
clientBaseClient?HTTP client from the http package. Defaults to null.
livePreviewMap<String, dynamic>?Live Preview settings. Defaults to null.

The stack page describes each argument and what the constructor checks.

Class-Level Notes

Region and host.

  • region takes one of four Region values. The constructor turns it into the delivery host, as the table below shows.
RegionDefault hostWith a custom host
Region.uscdn.contentstack.iothe custom host
Region.eueu-cdn.contentstack.comeu-<host>
Region.azure_naazure-na.contentstack.comazure-na-<host>
Region.gcp_nagcp-na-cdn.contentstack.comgcp-na-cdn.contentstack.com, whatever the custom host
  • Region has no value for AU, Azure EU or GCP EU. For those regions, keep Region.us and pass the delivery host of your region as host.
  • Every request goes to https://<host>/<apiVersion>/.... The setHost method replaces the host after construction.

Headers.

  • The constructor sends your credentials as the api_key, access_token and environment headers on every request. It adds a branch header when branch is not empty.
  • Every object you create from a stack shares the header map of that stack. The setHeader and removeHeader methods change every later request from the stack, including requests from objects you created earlier.

Live Preview.

  • Pass a livePreview map to the constructor with three keys. Set enable to true, authorization to a management token, and host to the Live Preview host.
  • When the map has an enable key, the constructor throws Exception if authorization or host is missing or empty.
  • Before you fetch an entry for preview, add a content_type_uid key and, optionally, a live_preview key (the preview hash) to stack.livePreview. When enable is true and content_type_uid is missing, the entry fetch and the query find throw ArgumentError.
  • On the first preview request, the SDK removes the access_token and environment headers, adds an authorization header, and switches the host to the Live Preview host. The stack keeps these changes for every later request.
  • Known issue: On a stack with any livePreview map, a query find without type arguments returns null. After the first preview request, sync, paginationToken and globalField throw TypeError. Use one Stack with livePreview for preview requests and a second Stack without it for all other requests.

Sync.

  • sync, paginationToken and syncToken each send one request to the Sync API and return one batch.
  • The SDK does not fetch the remaining batches. Pass each pagination_token to paginationToken until a response contains a sync_token, then store that token for your next syncToken call.
  • Pass the type arguments <contentstack.SyncResult, void> to any of the three methods to get a SyncResult instead of a map. The table below lists its fields.
FieldTypeJSON keyDescription
itemsList?itemsThe synced entries and assets of this batch, as maps.
skipint?skipThe number of items before this batch.
limitint?limitThe maximum number of items in one batch.
totalCountint?total_countThe total number of items in the sync.
syncTokenString?sync_tokenThe token for your next sync. Present on the last batch.
paginationTokenString?pagination_tokenThe token for the next batch. Present while batches remain.
  • syncresult.dart also defines the Items and Data classes. The SDK never builds them, and SyncResult.items contains plain maps.
  • Known issue: Items.fromJson reads the keys eventAt and contentTypeUid, so for a sync item both fields are null. Read item['event_at'] and item['content_type_uid'] from the map in items instead.

PublishType values.

  • The publishType argument of sync takes a PublishType value. The main library does not export PublishType, so import it with import 'package:contentstack/src/sync/publishtype.dart';.
  • The table below lists the seven values and the string sync sends for each.
ValueString the SDK sends
PublishType.AssetPublishedasset_published
PublishType.EntryPublishedentry_published
PublishType.AssetUnpublishedasset_unpublished
PublishType.AssetDeletedasset_deleted
PublishType.EntryUnpublishedentry_unpublished
PublishType.EntryDeletedentry_deleted
PublishType.ContentTypeDeletedcontent_type_deleted

Capability Matrix

CapabilitySupportedNotes / Alternative
Fetch every sync batch in one callNoPass each pagination_token to paginationToken
AU, Azure EU and GCP EU as Region valuesNoKeep Region.us and pass the delivery host of your region as host
Send Content Delivery API requests through your own clientNoSee the Known issue on stack
Filter the content type list with getContentTypesNoUse stack.contentType().query() and the ContentTypeQuery methods
Retry on 429NoImplement backoff in your calling code

Class-Level Properties Table

PropertyTypeAccessDefaultDescription
headersMap<String, String>?Read and writeapi_key, access_token and environment, plus branch when setThe headers the SDK sends on every request. Change them with setHeader and removeHeader. Assigning a new map to headers does not change the requests.
branchString?Read-onlynullThe branch you passed to the constructor.
regionRegionRead-onlyRegion.usThe region you passed to the constructor.
apiVersionStringRead-only'v3'The API version segment of every request path.
livePreviewMap<String, dynamic>?Read and writenullThe Live Preview settings. getLivePreview returns the same map.

Method Index

The groups below follow what you want to do. Every method is available on every Stack instance.

Create and configure the stack. Available on every instance. The setters change the requests that follow and make no request.

Method NameReturnsDescription
stackA new stack.Creates a stack from your credentials and options.
setHeaderNothing. The stack uses the change on its next request.Adds or replaces one request header.
removeHeaderNothing. The stack uses the change on its next request.Removes one request header.
setHostNothing. The stack uses the change on its next request.Replaces the delivery host.

Read the configuration. Available on every instance. These are getters, so read them without parentheses.

Method NameReturnsDescription
apiKeyThe stack's API key.Reads the API key.
deliveryTokenThe stack's delivery token.Reads the delivery token.
environmentThe stack's environment.Reads the environment.
hostThe stack's delivery host.Reads the delivery host.
endpointThe stack's delivery host.Reads the delivery host under a second name.
getLivePreviewThe stack's Live Preview map.Reads the Live Preview settings.

Open a content module. Available on every instance. These return an object and make no request. The request runs on the fetch or find call you chain to it.

Method NameReturnsDescription
contentTypeA new content type for the given UID.Opens one content type, or the list of them.
assetA new asset for the given UID.Opens one asset by its UID.
assetQueryA new query for the stack's assets.Opens a query across the assets of the stack.
imageTransformA new image transformation for the given URL.Holds an image URL and its transformation parameters.

Read stack-level content. Available on every instance. These send the request and return the decoded response.

Method NameReturnsDescription
getContentTypesThe content types in the stack.Lists every content type of the stack.
globalFieldThe requested global field, or every global field.Reads one global field, or lists them all.

Synchronize content. Available on every instance. These send the request and return one batch.

Method NameReturnsDescription
syncThe first batch of synced items.Starts a sync of the published content.
paginationTokenThe next batch of synced items.Continues a sync with a pagination token.
syncTokenThe items changed since the last sync.Fetches the changes since a sync token.

Request a preview entry. Available on every instance. It acts only when livePreview contains enable: true.

Method NameReturnsDescription
livePreviewQueryNothing. The stack starts the preview request in the background.Requests one entry from the Live Preview host.

Class-Level Snippet

This snippet creates a stack for the EU region on a branch, fetches one entry, and starts a sync.

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}');

  try {
    // contentType and entry make no request. fetch sends it.
    final response = await stack
        .contentType('<CONTENT_TYPE_UID>')
        .entry(entryUid: '<ENTRY_UID>')
        .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']);
    }

    // The first sync batch, as a SyncResult
    final batch = await stack.sync<contentstack.SyncResult, void>();
    print('items in this batch: ${batch?.items?.length}');
  } catch (e) {
    // Thrown for a non-JSON response, a network failure or a 30-second timeout
    print('Request did not complete: $e');
  }
}

Methods

Each method of the Stack class has its own section below, with its parameters, validation rules, behavior, and examples.

apiKey

apiKey returns the API key you passed to the Stack constructor.

This method takes no parameters.

Returns: String. The stack's API key.

Validation

  • There is no client-side validation. apiKey cannot fail, because the constructor already rejects an API key with no letter, digit or underscore.
  • apiKey is a getter. stack.apiKey() with parentheses does not compile.

Behavior

  • Client-side only. apiKey makes no request.
  • It returns the constructor argument. The SDK sends the same value in the api_key header.
  • No method changes the value. After removeHeader removes the api_key header, apiKey still returns the original key.

Example

Basic usage: read the API key back

import 'package:contentstack/contentstack.dart' as contentstack;

Future<void> main() async {
  final stack = contentstack.Stack('<API_KEY>', '<DELIVERY_TOKEN>', '<ENVIRONMENT>');

  // A getter: no parentheses
  print('API key: ${stack.apiKey}');
}

asset

asset opens one asset of the stack by its UID.

NameTypeDescription
uid (required)String?

UID of the asset. fetch needs it.

Default: Not applicable

Returns: Asset. A new asset for the given UID.

Validation

  • There is no client-side validation. asset accepts null and an empty string and makes no request.
  • The fetch method of the asset throws Exception if the UID is null or empty, because it requests one asset by its UID.
  • An unknown UID surfaces on fetch, as a result with an error_code key.

Behavior

  • Client-side only. asset builds an Asset object and makes no request.
  • The object reads the environment and the API version from the stack when you create it.
  • See the Asset class page for the settings and the request. To list assets, use the assetQuery method.

Example

Basic usage: fetch one asset

import 'package:contentstack/contentstack.dart' as contentstack;

Future<void> main() async {
  final stack = contentstack.Stack('<API_KEY>', '<DELIVERY_TOKEN>', '<ENVIRONMENT>');
  final asset = stack.asset('<ASSET_UID>');

  try {
    final response = await asset.fetch();
    if (response is Map && response.containsKey('error_code')) {
      // The API rejected the request, for example because the UID does not exist
      print('Request failed: ${response['error_code']} ${response['error_message']}');
    } else {
      print(response['asset']['url']);
    }
  } 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');
  }
}

assetQuery

assetQuery opens a query across the assets of the stack.

This method takes no parameters.

Returns: AssetQuery. A new query for the stack's assets.

Validation

  • There is no client-side validation. assetQuery cannot fail and makes no request.
  • Errors come from the find call that follows. An API rejection comes back as the result with an error_code key, not as an exception.

Behavior

  • Client-side only. assetQuery builds an AssetQuery object and makes no request.
  • The object reads the environment and the API version from the stack when you create it.
  • The main library does not export AssetQuery. Hold the result in a final or var variable. To write the type name, add import 'package:contentstack/src/asset_query.dart';.
  • See the AssetQuery class page for the settings and the request.

Example

Basic usage: list the first five assets

import 'package:contentstack/contentstack.dart' as contentstack;

Future<void> main() async {
  final stack = contentstack.Stack('<API_KEY>', '<DELIVERY_TOKEN>', '<ENVIRONMENT>');
  final query = stack.assetQuery()..limit(5);

  try {
    final response = await query.find();
    if (response is Map && response.containsKey('error_code')) {
      // The API rejected the request
      print('Request failed: ${response['error_code']} ${response['error_message']}');
    } else {
      for (final asset in response['assets']) {
        print(asset['url']);
      }
    }
  } catch (e) {
    // Thrown for a non-JSON response, a network failure or a 30-second timeout
    print('Request did not complete: $e');
  }
}

contentType

contentType opens one content type by its UID, or the list of content types when you omit the UID.

NameTypeDescription
contentTypeIdString?

UID of the content type. null opens the content type list.

Default: null

Returns: ContentType. A new content type for the given UID.

Validation

  • There is no client-side validation. contentType accepts any string and makes no request.
  • Without a UID, or with an empty string, the content type has no path. Its fetch then throws Exception, and the entry you open from it cannot reach the API. Its query still works, because it lists every content type.
  • An unknown UID surfaces on the request you chain, as a result with an error_code key.

Behavior

  • Client-side only. contentType builds a ContentType object and makes no request.
  • The object reads the environment and the API version from the stack when you create it.
  • Use the result to fetch the schema of the content type, open its entries, or query the content types of the stack. See the ContentType class page for its methods.

Example

Basic usage: fetch one entry of a content type

import 'package:contentstack/contentstack.dart' as contentstack;

Future<void> main() async {
  final stack = contentstack.Stack('<API_KEY>', '<DELIVERY_TOKEN>', '<ENVIRONMENT>');
  final contentType = stack.contentType('<CONTENT_TYPE_UID>');

  try {
    final response = await contentType.entry(entryUid: '<ENTRY_UID>').fetch();
    if (response is Map && response.containsKey('error_code')) {
      // The API rejected the request, for example because the UID does not exist
      print('Request failed: ${response['error_code']} ${response['error_message']}');
    } else {
      print(response['entry']['title']);
    }
  } catch (e) {
    // Thrown for a non-JSON response, a network failure or a 30-second timeout
    print('Request did not complete: $e');
  }
}

No UID: list the content types of the stack

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().query().find();
  for (final item in response['content_types']) {
    print(item['uid']);
  }
}

deliveryToken

deliveryToken returns the delivery token you passed to the Stack constructor.

This method takes no parameters.

Returns: String. The stack's delivery token.

Validation

  • There is no client-side validation. deliveryToken cannot fail, because the constructor already rejects a delivery token with no letter, digit or underscore.
  • deliveryToken is a getter. stack.deliveryToken() with parentheses does not compile.

Behavior

  • Client-side only. deliveryToken makes no request.
  • It returns the constructor argument. The SDK sends the same value in the access_token header.
  • No method changes the value. After a Live Preview request removes the access_token header, deliveryToken still returns the original token. See Live Preview on the Stack class page.

Example

Basic usage: read the delivery token back

import 'package:contentstack/contentstack.dart' as contentstack;

Future<void> main() async {
  final stack = contentstack.Stack('<API_KEY>', '<DELIVERY_TOKEN>', '<ENVIRONMENT>');

  // A getter: no parentheses
  print('Delivery token: ${stack.deliveryToken}');
}

endpoint

endpoint returns the delivery host that the stack sends its next request to, the same value as host.

This method takes no parameters.

Returns: String. The stack's delivery host.

Validation

  • There is no client-side validation. endpoint cannot fail.
  • endpoint returns null only when you passed host: null with Region.us.
  • endpoint is a getter. stack.endpoint() with parentheses does not compile.

Behavior

  • Client-side only. endpoint makes no request.
  • It returns the value of the host getter. It is a host name, not a URL: it has no scheme and no API version, for example eu-cdn.contentstack.com.
  • Every request goes to https://<endpoint>/<apiVersion>/.... Read apiVersion from the stack to build the full base URL.

Example

Basic usage: build the base URL of the requests

import 'package:contentstack/contentstack.dart' as contentstack;

Future<void> main() async {
  final stack = contentstack.Stack(
    '<API_KEY>',
    '<DELIVERY_TOKEN>',
    '<ENVIRONMENT>',
    region: contentstack.Region.eu,
  );

  // A getter: no parentheses
  print('https://${stack.endpoint}/${stack.apiVersion}'); // https://eu-cdn.contentstack.com/v3
}

environment

environment returns the environment you passed to the Stack constructor.

This method takes no parameters.

Returns: String. The stack's environment.

Validation

  • There is no client-side validation. environment cannot fail, because the constructor already rejects an environment with no letter, digit or underscore.
  • environment is a getter. stack.environment() with parentheses does not compile.

Behavior

  • Client-side only. environment makes no request.
  • It returns the constructor argument. The SDK sends the same value in the environment header. Most requests, for example a sync, also send it as the environment query parameter.
  • No method changes the value. After removeHeader removes the environment header, environment still returns the original name, but later requests no longer carry it in the header.

Example

Basic usage: read the environment back

import 'package:contentstack/contentstack.dart' as contentstack;

Future<void> main() async {
  final stack = contentstack.Stack('<API_KEY>', '<DELIVERY_TOKEN>', '<ENVIRONMENT>');

  // A getter: no parentheses
  print('Environment: ${stack.environment}');
}

getContentTypes

getContentTypes returns every content type of the stack in one request.

NameTypeDescription
queryParameters (required)Map

Query parameters for the request. The SDK does not send them.

Default: Not applicable

Returns: Future<T>. The content types in the stack.

Validation

  • There is no client-side validation. getContentTypes does not read queryParameters, so every map, including an empty one, produces the same request.
  • Errors come from the request itself.
    • getContentTypes throws only when the request does not complete: a network failure, a 30-second timeout or a response that is not JSON.
    • An API rejection comes back as the result with an error_code key. It does not throw.
    • Check the result for an error_code key even inside a try block.

Additional Resource Refer to Content Delivery API Errors for the full error code list.

Behavior

  • Known issue: getContentTypes does not send queryParameters, so options such as include_count or include_global_field_schema have no effect. Use stack.contentType().query() with the includeCount and includeGlobalField methods, then call find.
  • One call sends one Get all content types request, GET /<apiVersion>/content_types, with no query string. The environment travels in the environment header.
  • The result is the decoded JSON body as a Map. The content types are in its content_types list.
  • The SDK has no model class for content types. Call getContentTypes without type arguments.

Example

Basic usage: list the content type UIDs

import 'package:contentstack/contentstack.dart' as contentstack;

Future<void> main() async {
  final stack = contentstack.Stack('<API_KEY>', '<DELIVERY_TOKEN>', '<ENVIRONMENT>');

  try {
    final response = await stack.getContentTypes({});
    if (response is Map && response.containsKey('error_code')) {
      // The API rejected the request
      print('Request failed: ${response['error_code']} ${response['error_message']}');
    } else {
      for (final contentType in response['content_types']) {
        print(contentType['uid']);
      }
    }
  } catch (e) {
    // Thrown for a non-JSON response, a network failure or a 30-second timeout
    print('Request did not complete: $e');
  }
}

Workaround: list content types with a count and global field schemas

import 'package:contentstack/contentstack.dart' as contentstack;

Future<void> main() async {
  final stack = contentstack.Stack('<API_KEY>', '<DELIVERY_TOKEN>', '<ENVIRONMENT>');
  final query = stack.contentType().query()
    ..includeCount()
    ..includeGlobalField();

  final response = await query.find();
  print('content types: ${response['count']}');
}

getLivePreview

getLivePreview returns the Live Preview map that the stack holds.

This method takes no parameters.

Returns: Map. The stack's Live Preview map.

Validation

  • There is no client-side validation. getLivePreview cannot fail.
  • getLivePreview returns null when you created the stack without livePreview.
  • getLivePreview is a getter, despite its name. stack.getLivePreview() with parentheses does not compile.

Behavior

  • Client-side only. getLivePreview makes no request.
  • It returns the same map object as the livePreview property, not a copy. A change you make through the returned map, for example adding content_type_uid, changes the settings that the next preview request reads.
  • See Live Preview on the Stack class page for the keys that a preview request reads.

Example

Basic usage: read the Live Preview settings

import 'package:contentstack/contentstack.dart' as contentstack;

Future<void> main() async {
  final stack = contentstack.Stack(
    '<API_KEY>',
    '<DELIVERY_TOKEN>',
    '<ENVIRONMENT>',
    livePreview: <String, dynamic>{
      'enable': true,
      'authorization': '<MANAGEMENT_TOKEN>',
      'host': '<HOST>',
    },
  );

  // A getter: no parentheses
  final settings = stack.getLivePreview;
  print('Live Preview host: ${settings?['host']}');
}

Set the content type to preview through the returned map

import 'package:contentstack/contentstack.dart' as contentstack;

Future<void> main() async {
  final stack = contentstack.Stack(
    '<API_KEY>',
    '<DELIVERY_TOKEN>',
    '<ENVIRONMENT>',
    livePreview: <String, dynamic>{
      'enable': true,
      'authorization': '<MANAGEMENT_TOKEN>',
      'host': '<HOST>',
    },
  );

  // The returned map is the stack's own map, so the next preview request reads this key
  stack.getLivePreview?['content_type_uid'] = '<CONTENT_TYPE_UID>';
  print(stack.livePreview?['content_type_uid']);
}

globalField

globalField returns one global field by its UID, or every global field of the stack when you omit the UID.

NameTypeDescription
globalFieldUidString?

UID of the global field. null lists every global field.

Default: null
includeBranchbool

Adds the _branch key to the response.

Default: false

Returns: Future<T>. The requested global field, or every global field.

Validation

  • There is no client-side validation of the arguments.
  • An empty globalFieldUid lists every global field, the same as null, and raises no error.
  • Throws TypeError if the stack has no environment header, because globalField reads the environment from the header map with a null check. The header is missing after removeHeader removes it, or after a Live Preview request.
  • Errors from the request:
    • globalField throws only when the request does not complete: a network failure, a 30-second timeout or a response that is not JSON.
    • An API rejection, for example an unknown UID, comes back as the result with an error_code key. It does not throw.
    • Check the result for an error_code key even inside a try block.

Additional Resource Refer to Content Delivery API Errors for the full error code list.

Behavior

  • One call sends one request.
  • globalField sends the environment as the environment query parameter. With includeBranch set to true, it also sends include_branch=true, and the API adds the _branch key that names the branch of the global field.
  • Both arguments are optional positional. To list every global field with the branch key, pass null first: stack.globalField(null, true).
  • The result is the decoded JSON body as a Map. The SDK has no model class for global fields, so call globalField without type arguments.

Limitations

  • Does not send include_global_field_schema, the parameter that the API reference describes for adding the schema of the global field to the response. The SDK offers no way to add it to this request.

Example

Basic usage: read one global field

import 'package:contentstack/contentstack.dart' as contentstack;

Future<void> main() async {
  final stack = contentstack.Stack('<API_KEY>', '<DELIVERY_TOKEN>', '<ENVIRONMENT>');

  try {
    final response = await stack.globalField('<GLOBAL_FIELD_UID>');
    if (response is Map && response.containsKey('error_code')) {
      // The API rejected the request, for example because the UID does not exist
      print('Request failed: ${response['error_code']} ${response['error_message']}');
    } else {
      print(response['global_field']['title']);
    }
  } catch (e) {
    // Thrown for a missing environment header, a non-JSON response, a network failure or a 30-second timeout
    print('Request did not complete: $e');
  }
}

All parameters: one global field with its branch

import 'package:contentstack/contentstack.dart' as contentstack;

Future<void> main() async {
  final stack = contentstack.Stack(
    '<API_KEY>',
    '<DELIVERY_TOKEN>',
    '<ENVIRONMENT>',
    branch: '<BRANCH>',
  );

  final response = await stack.globalField('<GLOBAL_FIELD_UID>', true);
  print(response['global_field']['_branch']);
}

No UID: list every global field

import 'package:contentstack/contentstack.dart' as contentstack;

Future<void> main() async {
  final stack = contentstack.Stack('<API_KEY>', '<DELIVERY_TOKEN>', '<ENVIRONMENT>');

  final response = await stack.globalField();
  for (final globalField in response['global_fields']) {
    print(globalField['uid']);
  }
}

host

host returns the delivery host that the stack sends its next request to.

This method takes no parameters.

Returns: String. The stack's delivery host.

Validation

  • There is no client-side validation. host cannot fail.
  • host returns null only when you passed host: null with Region.us.
  • host is a getter. stack.host() with parentheses does not compile.

Behavior

  • Client-side only. host makes no request.
  • It returns the host name only, with no scheme and no API version, for example cdn.contentstack.io.
  • The constructor derives the value from region and host. See Region and host on the Stack class page.
  • The value changes after setHost, and after the first Live Preview request, which switches the stack to the Live Preview host.
  • The endpoint getter returns the same value.

Example

Basic usage: read the host for a region

import 'package:contentstack/contentstack.dart' as contentstack;

Future<void> main() async {
  final stack = contentstack.Stack(
    '<API_KEY>',
    '<DELIVERY_TOKEN>',
    '<ENVIRONMENT>',
    region: contentstack.Region.azure_na,
  );

  // A getter: no parentheses
  print('Host: ${stack.host}'); // azure-na.contentstack.com
}

Read the host after setHost

import 'package:contentstack/contentstack.dart' as contentstack;

Future<void> main() async {
  final stack = contentstack.Stack('<API_KEY>', '<DELIVERY_TOKEN>', '<ENVIRONMENT>');
  stack.setHost('<HOST>');

  print('Host: ${stack.host}'); // the host you passed to setHost
}

imageTransform

imageTransform holds an image URL so that you can add Image Delivery API parameters to it.

NameTypeDescription
imageUrl (required)String

URL of an image asset of the stack.

Default: Not applicable

Returns: ImageTransformation. A new image transformation for the given URL.

Validation

  • There is no client-side validation in imageTransform. It accepts any string.
  • getUrl throws ArgumentError if imageUrl is empty, because it has no URL to add the parameters to.

Behavior

  • Client-side only. imageTransform builds an ImageTransformation object and makes no request.
  • Pass the url of an asset, for example the value that an asset fetch returns under asset.url.
  • The transformation does not use the stack credentials. It only builds a URL from imageUrl and the parameters you add.
  • See the ImageTransformation class page for the parameters you can add, such as resize, convert and quality.

Example

Basic usage: build a resized image URL

import 'package:contentstack/contentstack.dart' as contentstack;

Future<void> main() async {
  final stack = contentstack.Stack('<API_KEY>', '<DELIVERY_TOKEN>', '<ENVIRONMENT>');
  final image = stack.imageTransform('<IMAGE_URL>')..resize(width: 320);

  // getUrl builds the URL and makes no request
  print(image.getUrl());
}

livePreviewQuery

livePreviewQuery starts a background request for one entry from the Live Preview host and stores the entry in the Live Preview map of the stack.

NameTypeDescription
livePreviewQuery (required)Map<String, dynamic>

Keys content_type_uid, entry_uid and host of the entry to preview.

Default: Not applicable

Returns: void. Nothing. The stack starts the preview request in the background.

Validation

  • Throws TypeError if the stack has no livePreview map, because livePreviewQuery reads the map with a null check.
  • Throws TypeError if the enable value in livePreview is not a bool.
  • Does nothing, with no error, when livePreview has no enable key, when enable is false, or when the argument has no content_type_uid.
  • Failures of the background request never reach your code. livePreviewQuery returns before the request runs and does not wait for it, so a failure becomes an uncaught asynchronous error.

Additional Resource Refer to Content Delivery API Errors for the full error code list.

Behavior

  • Known issue: livePreviewQuery builds a malformed request URL. It never loads the preview entry, and the failed background request becomes an uncaught error that can stop your app. To preview an entry, add content_type_uid to stack.livePreview and call fetch on the entry, as the second example below shows.
  • When enable is true and the argument has a content_type_uid, livePreviewQuery starts a GET request for that entry: /<apiVersion>/content_types/<content_type_uid>/entries/<entry_uid>.
  • The request goes to the host in the argument, not the host in livePreview.
  • The request sends the api_key header and the authorization header of the stack. The stack holds authorization only after an earlier preview request, so before that the background request fails.
  • On success, the method stores the entry of the response under the entry key of stack.livePreview.
  • livePreviewQuery does not store content_type_uid or entry_uid in stack.livePreview, so it does not prepare the entry fetch for preview.

Example

Basic usage: request a preview entry

import 'package:contentstack/contentstack.dart' as contentstack;

Future<void> main() async {
  final stack = contentstack.Stack(
    '<API_KEY>',
    '<DELIVERY_TOKEN>',
    '<ENVIRONMENT>',
    livePreview: <String, dynamic>{
      'enable': true,
      'authorization': '<MANAGEMENT_TOKEN>',
      'host': '<HOST>',
    },
  );

  try {
    // Returns at once. See the Known issue: the entry does not arrive,
    // and the background request fails with an uncaught error.
    stack.livePreviewQuery(<String, dynamic>{
      'content_type_uid': '<CONTENT_TYPE_UID>',
      'entry_uid': '<ENTRY_UID>',
      'host': '<HOST>',
    });
  } on TypeError catch (e) {
    // Thrown when the stack has no livePreview map or enable is not a bool
    print('Live Preview is not configured: $e');
  }
}

Workaround: preview an entry through fetch

import 'package:contentstack/contentstack.dart' as contentstack;

Future<void> main() async {
  final stack = contentstack.Stack(
    '<API_KEY>',
    '<DELIVERY_TOKEN>',
    '<ENVIRONMENT>',
    livePreview: <String, dynamic>{
      'enable': true,
      'authorization': '<MANAGEMENT_TOKEN>',
      'host': '<HOST>',
    },
  );
  // The entry fetch reads this key and sends the request to the Live Preview host
  stack.livePreview?['content_type_uid'] = '<CONTENT_TYPE_UID>';

  final response = await stack
      .contentType('<CONTENT_TYPE_UID>')
      .entry(entryUid: '<ENTRY_UID>')
      .fetch();
  print(response['entry']['title']);
}

paginationToken

paginationToken returns the next batch of a sync, from the pagination token of the previous batch.

NameTypeDescription
paginationToken (required)String?

Pagination token from the previous sync batch.

Default: Not applicable

Returns: Future<T>. The next batch of synced items.

Validation

  • There is no client-side validation of the token. A null or empty token sends the request with no pagination_token, which the Sync using pagination token request requires.
  • Throws TypeError if the stack has no environment header, because paginationToken copies the environment from the header map into a map that does not accept null. The header is missing after removeHeader removes it, or after a Live Preview request.
  • Errors from the request:
    • paginationToken throws only when the request does not complete: a network failure, a 30-second timeout or a response that is not JSON.
    • An API rejection, for example an expired token, comes back as the result with an error_code key. It does not throw.
    • Check the result for an error_code key even inside a try block.

Additional Resource Refer to Content Delivery API Errors for the full error code list.

Behavior

  • One call sends one Sync using pagination token request, GET /<apiVersion>/stacks/sync, with pagination_token and the environment query parameter.
  • The API returns the next batch of up to 100 records. The body holds another pagination_token while batches remain, and a sync_token on the last batch.
  • paginationToken returns one batch. It does not fetch the batches after it. Call it again with each new pagination_token.
  • Use the token to restart a sync that stopped partway, for example after a network failure.
  • With the type arguments <contentstack.SyncResult, void>, paginationToken returns a SyncResult, with the batch in items and the next token in paginationToken or syncToken. See Sync on the Stack class page for every field.
  • Known issue: With <contentstack.SyncResult, void>, an API rejection returns a SyncResult with every field null and no sign of the error. Call paginationToken without type arguments when you need to read the error.

Example

Basic usage: fetch the next batch

import 'package:contentstack/contentstack.dart' as contentstack;

Future<void> main() async {
  final stack = contentstack.Stack('<API_KEY>', '<DELIVERY_TOKEN>', '<ENVIRONMENT>');

  try {
    final response = await stack.paginationToken('<PAGINATION_TOKEN>');
    if (response is Map && response.containsKey('error_code')) {
      // The API rejected the request, for example because the token expired
      print('Request failed: ${response['error_code']} ${response['error_message']}');
    } else {
      print('items in this batch: ${response['items'].length}');
      print('sync token: ${response['sync_token']}');
    }
  } catch (e) {
    // Thrown for a missing environment header, a non-JSON response, a network failure or a 30-second timeout
    print('Request did not complete: $e');
  }
}

Resume a sync until the last batch

import 'package:contentstack/contentstack.dart' as contentstack;

Future<void> main() async {
  final stack = contentstack.Stack('<API_KEY>', '<DELIVERY_TOKEN>', '<ENVIRONMENT>');

  var response = await stack.paginationToken('<PAGINATION_TOKEN>');
  while (response['pagination_token'] != null) {
    print('items in this batch: ${response['items'].length}');
    response = await stack.paginationToken(response['pagination_token']);
  }
  print('sync token: ${response['sync_token']}');
}

removeHeader

removeHeader removes one header from every later request from the stack.

NameTypeDescription
headerKey (required)String

Name of the header to remove.

Default: Not applicable

Returns: void. Nothing. The stack uses the change on its next request.

Validation

  • There is no client-side validation. removeHeader cannot fail. A name the map does not hold, including an empty string, changes nothing.
  • Removing a credential header does not raise an error here. The next request fails instead.
    • Without api_key or access_token, the API rejects the request, and the rejection comes back as the result with an error_code key.
    • Without environment, sync, paginationToken and globalField throw TypeError, because they read the environment from the header map.

Behavior

  • Client-side only. removeHeader deletes the key from the header map of the stack and makes no request.
  • Every object you create from the stack shares that map, so the change also reaches requests from objects you created before the call.
  • The SDK sets Content-Type and X-User-Agent again before every request, so removing either one has no effect.
  • The getters apiKey, deliveryToken and environment keep returning the constructor values.

Example

Basic usage: stop sending a branch header

import 'package:contentstack/contentstack.dart' as contentstack;

Future<void> main() async {
  final stack = contentstack.Stack(
    '<API_KEY>',
    '<DELIVERY_TOKEN>',
    '<ENVIRONMENT>',
    branch: '<BRANCH>',
  );
  // Later requests read from the default branch
  stack.removeHeader('branch');
  print(stack.headers);

  try {
    final response = await stack
        .contentType('<CONTENT_TYPE_UID>')
        .entry(entryUid: '<ENTRY_UID>')
        .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 non-JSON response, a network failure or a 30-second timeout
    print('Request did not complete: $e');
  }
}

setHeader

setHeader adds a header to every later request from the stack, or replaces the header of that name.

NameTypeDescription
key (required)String

Name of the header.

Default: Not applicable
value (required)String?

Value of the header. null throws TypeError.

Default: Not applicable

Returns: void. Nothing. The stack uses the change on its next request.

Validation

  • setHeader makes no change and raises no error when key or value is an empty string.
  • Throws TypeError if value is null and key is not empty, because setHeader reads the value with a null check before it tests its length.
  • setHeader does not check the name or the value against the API. A header the API rejects surfaces on the next request, as a result with an error_code key.

Behavior

  • Client-side only. setHeader writes the header into the header map of the stack and makes no request.
  • Every object you create from the stack shares that map, so the header also reaches requests from objects you created before the call.
  • A key that already exists gets the new value. For example, setHeader('branch', '<BRANCH>') replaces the branch that the constructor set.
  • The SDK sets Content-Type and X-User-Agent itself before every request, so setHeader cannot change those two headers.
  • The getters apiKey, deliveryToken and environment keep returning the constructor values after you replace the matching header.

Example

Basic usage: read entries from a branch

import 'package:contentstack/contentstack.dart' as contentstack;

Future<void> main() async {
  final stack = contentstack.Stack('<API_KEY>', '<DELIVERY_TOKEN>', '<ENVIRONMENT>');
  // Every later request from this stack sends the branch header
  stack.setHeader('branch', '<BRANCH>');

  try {
    final response = await stack
        .contentType('<CONTENT_TYPE_UID>')
        .entry(entryUid: '<ENTRY_UID>')
        .fetch();
    if (response is Map && response.containsKey('error_code')) {
      // The API rejected the request, for example because the branch does not exist
      print('Request failed: ${response['error_code']} ${response['error_message']}');
    } else {
      print(response['entry']['title']);
    }
  } catch (e) {
    // Thrown for a non-JSON response, a network failure or a 30-second timeout
    print('Request did not complete: $e');
  }
}

Edge case: a missing header value

import 'package:contentstack/contentstack.dart' as contentstack;

Future<void> main() async {
  final stack = contentstack.Stack('<API_KEY>', '<DELIVERY_TOKEN>', '<ENVIRONMENT>');
  String? branch; // for example, a setting your app did not find

  try {
    stack.setHeader('branch', branch);
  } on TypeError catch (e) {
    // Thrown when the value is null
    print('Header value missing: $e');
  }
  print(stack.headers);
}

setHost

setHost replaces the host that every later request from the stack goes to.

NameTypeDescription
host (required)String

Host name, with no scheme and no path.

Default: Not applicable

Returns: void. Nothing. The stack uses the change on its next request.

Validation

  • setHost makes no change and raises no error when host is an empty string.
  • There is no other client-side validation. A host that does not resolve fails on the next request with a network exception from the http package. A host that answers with something other than JSON makes the request throw Exception or FormatException.

Behavior

  • Client-side only. setHost stores the host and makes no request.
  • Every object you create from the stack reads the host when it sends a request, so the new host also applies to objects you created before the call.
  • setHost uses the string as given. It does not add the region prefix that the constructor adds. See Region and host on the Stack class page.
  • Pass a host name such as eu-cdn.contentstack.com. The SDK builds https://<host>/<apiVersion>/... from it, so a value with https:// or a path produces a wrong URL.
  • The first Live Preview request calls setHost with the Live Preview host and replaces your value.
  • The host and endpoint getters return the new value.

Example

Basic usage: send requests to another delivery host

import 'package:contentstack/contentstack.dart' as contentstack;

Future<void> main() async {
  final stack = contentstack.Stack('<API_KEY>', '<DELIVERY_TOKEN>', '<ENVIRONMENT>');
  // Every later request goes to this host
  stack.setHost('<HOST>');

  try {
    final response = await stack
        .contentType('<CONTENT_TYPE_UID>')
        .entry(entryUid: '<ENTRY_UID>')
        .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 host that does not resolve, a non-JSON response or a 30-second timeout
    print('Request did not complete: $e');
  }
}

stack

Stack creates a stack from your API key, delivery token and environment, with optional settings for the API version, region, branch, host, HTTP client and Live Preview.

NameTypeDescription
apiKey (required)String

API key of the stack.

Default: Not applicable
deliveryToken (required)String

Delivery token of the environment.

Default: Not applicable
environment (required)String

Environment to read published content from.

Default: Not applicable
apiVersionString (named)

API version segment of every request path.

Default: 'v3'
regionRegion (named)

Region that picks the delivery host.

Default: Region.us
branchString? (named)

Branch to read content from. null sends no branch header.

Default: null
hostString? (named)

Delivery host. region can add a prefix to it.

Default: 'cdn.contentstack.io'
clientBaseClient? (named)

HTTP client from the http package.

Default: null
livePreviewMap<String, dynamic>? (named)

Live Preview settings: enable, authorization, host.

Default: null

Returns: Stack. A new stack.

Validation

  • Throws ArgumentError if apiKey, deliveryToken or environment contains no letter, digit or underscore, for example an empty string or ' '. The constructor strips every other character before the check, because a credential with no word character cannot identify a stack.
  • The constructor does not check that the credentials are valid. A wrong API key, token or environment surfaces at the first request. The API rejection comes back as the result with an error_code key, not as an exception.
  • Throws Exception if livePreview has an enable key but no authorization or host value. A preview request needs both.
  • With host: null and Region.us, the stack has no host, and the first request throws TypeError. Pass a host name or leave host unset.

Additional Resource Refer to Content Delivery API Errors for the full error code list.

Behavior

  • Client-side only. The constructor builds the headers and the host and makes no request.
  • The constructor sends apiKey, deliveryToken and environment as the api_key, access_token and environment headers on every request. It adds a branch header when branch is not empty.
  • The constructor derives the delivery host from region and host. See Region and host on the Stack class page for the mapping.
  • apiVersion becomes the first path segment of every request, for example https://cdn.contentstack.io/v3/content_types.
  • The constructor stores livePreview as given. See Live Preview on the Stack class page for the keys that a preview request reads.
  • Known issue: The SDK sends its Content Delivery API requests without the client you pass, so a proxy, logging or mock client has no effect on them. Only the image transformation fetch uses it. Wrap your calls in runWithClient from the http package to set the client that the other requests use.

Example

Basic usage: create a stack and fetch an entry

import 'package:contentstack/contentstack.dart' as contentstack;

Future<void> main() async {
  try {
    final stack = contentstack.Stack('<API_KEY>', '<DELIVERY_TOKEN>', '<ENVIRONMENT>');
    final entry = stack.contentType('<CONTENT_TYPE_UID>').entry(entryUid: '<ENTRY_UID>');

    final response = await entry.fetch();
    if (response is Map && response.containsKey('error_code')) {
      // The API rejected the request, for example because of a wrong API key
      print('Request failed: ${response['error_code']} ${response['error_message']}');
    } else {
      print(response['entry']['title']);
    }
  } on ArgumentError catch (e) {
    // Thrown by the constructor when a credential is empty
    print('Invalid credential: $e');
  } catch (e) {
    // Thrown for a non-JSON response, a network failure or a 30-second timeout
    print('Request did not complete: $e');
  }
}

Region, branch, host and API version

import 'package:contentstack/contentstack.dart' as contentstack;

Future<void> main() async {
  final stack = contentstack.Stack(
    '<API_KEY>',
    '<DELIVERY_TOKEN>',
    '<ENVIRONMENT>',
    apiVersion: 'v3',
    region: contentstack.Region.eu,
    branch: '<BRANCH>',
    host: 'cdn.contentstack.io',
  );

  // The default host with Region.eu resolves to the EU delivery host
  print(stack.host); // eu-cdn.contentstack.com
  print(stack.branch);
}

Live Preview and a custom HTTP client

Add the http package to your pubspec.yaml to import BaseClient. The SDK does not route its requests through this client (see the Known issue under Behavior). The program below passes a logging client and a Live Preview map to the constructor.

import 'package:contentstack/contentstack.dart' as contentstack;
import 'package:http/http.dart' as http;

class LoggingClient extends http.BaseClient {
  final http.Client _inner = http.Client();

  @override
  Future<http.StreamedResponse> send(http.BaseRequest request) {
    print('Sending ${request.url}');
    return _inner.send(request);
  }
}

Future<void> main() async {
  final stack = contentstack.Stack(
    '<API_KEY>',
    '<DELIVERY_TOKEN>',
    '<ENVIRONMENT>',
    client: LoggingClient(),
    livePreview: <String, dynamic>{
      'enable': true,
      'authorization': '<MANAGEMENT_TOKEN>',
      'host': '<HOST>',
    },
  );

  print(stack.getLivePreview);
}

sync

sync starts a sync and returns the first batch of entries and assets published to the environment.

NameTypeDescription
contentTypeUidString? (named)

Syncs only the entries of this content type.

Default: null
fromDateString? (named)

Start date of the sync, as an ISO 8601 string.

Default: null
localeString? (named)

Syncs only content in this locale.

Default: null
publishTypePublishType? (named)

Event type to sync, such as PublishType.EntryPublished.

Default: null

Returns: Future<T>. The first batch of synced items.

Validation

  • There is no client-side validation of the arguments. sync skips a null or empty string, so locale: '' sends no locale.
  • Throws TypeError if the stack has no environment header, because sync copies the environment from the header map into a map that does not accept null. The header is missing after removeHeader removes it, or after a Live Preview request.
  • Errors from the request:
    • sync throws only when the request does not complete: a network failure, a 30-second timeout or a response that is not JSON.
    • An API rejection comes back as the result with an error_code key. It does not throw.
    • Check the result for an error_code key even inside a try block.

Additional Resource Refer to Content Delivery API Errors for the full error code list.

Behavior

  • One call sends one Initial Sync request, GET /<apiVersion>/stacks/sync, with init=true, the environment query parameter, and each argument you pass.
  • contentTypeUid and locale reach the API as content_type_uid and locale. fromDate reaches it as from_date, and publishType as publish_type with the string from the PublishType table on the Stack class page, for example entry_published for PublishType.EntryPublished.
  • Known issue: sync sends from_date and publish_type, but the Initial Sync reference names these parameters start_from and type. Expect items of every date and event type, and filter the returned items in your app by event_at and type.
  • The result is the decoded JSON body as a Map. Its items list contains the synced entries and assets. When the sync includes more than 100 records, the body has a pagination_token for the next batch. Otherwise it has a sync_token for your next sync.
  • With the type arguments <contentstack.SyncResult, void>, sync returns a SyncResult, with the batch in items and the next token in paginationToken or syncToken. See Sync on the Stack class page for every field.
  • Known issue: With <contentstack.SyncResult, void>, an API rejection returns a SyncResult with every field null and no sign of the error. Call sync without type arguments when you need to read the error.
  • PublishType is not in the main library. Import it with import 'package:contentstack/src/sync/publishtype.dart';.

Limitations

  • Does not fetch every batch. Pass each pagination_token to the paginationToken method until a response contains a sync_token.

Example

Basic usage: sync everything published to the environment

import 'package:contentstack/contentstack.dart' as contentstack;

Future<void> main() async {
  final stack = contentstack.Stack('<API_KEY>', '<DELIVERY_TOKEN>', '<ENVIRONMENT>');

  try {
    final response = await stack.sync();
    if (response is Map && response.containsKey('error_code')) {
      // The API rejected the request
      print('Request failed: ${response['error_code']} ${response['error_message']}');
    } else {
      print('items in this batch: ${response['items'].length}');
      print('next batch: ${response['pagination_token']}');
    }
  } catch (e) {
    // Thrown for a missing environment header, a non-JSON response, a network failure or a 30-second timeout
    print('Request did not complete: $e');
  }
}

All parameters: one content type, locale and event type from a date

import 'package:contentstack/contentstack.dart' as contentstack;
import 'package:contentstack/src/sync/publishtype.dart';

Future<void> main() async {
  final stack = contentstack.Stack('<API_KEY>', '<DELIVERY_TOKEN>', '<ENVIRONMENT>');

  final response = await stack.sync(
    contentTypeUid: '<CONTENT_TYPE_UID>',
    fromDate: '2024-01-01T00:00:00.000Z',
    locale: '<LOCALE>',
    publishType: PublishType.EntryPublished,
  );
  // See the Known issue above: filter by date and event type in your app
  for (final item in response['items']) {
    if (item['type'] == 'entry_published') {
      print('${item['event_at']} ${item['data']['uid']}');
    }
  }
}

Complete sync: follow every pagination token with SyncResult

import 'package:contentstack/contentstack.dart' as contentstack;

Future<void> main() async {
  final stack = contentstack.Stack('<API_KEY>', '<DELIVERY_TOKEN>', '<ENVIRONMENT>');
  final items = <dynamic>[];

  var batch = await stack.sync<contentstack.SyncResult, void>();
  while (batch != null) {
    items.addAll(batch.items ?? []);
    final next = batch.paginationToken;
    if (next == null) break;
    batch = await stack.paginationToken<contentstack.SyncResult, void>(next);
  }

  print('synced items: ${items.length}');
  // Store the sync token and pass it to syncToken next time
  print('sync token: ${batch?.syncToken}');
}

syncToken

syncToken returns the entries and assets that changed since the sync that issued the token.

NameTypeDescription
syncToken (required)String?

Sync token from the last completed sync.

Default: Not applicable

Returns: Future<T>. The items changed since the last sync.

Validation

  • There is no client-side validation of the token. A null or empty token sends the request with no sync_token, which the Subsequent Sync request requires.
  • Errors from the request:
    • syncToken throws only when the request does not complete: a network failure, a 30-second timeout or a response that is not JSON.
    • An API rejection, for example an invalid token, comes back as the result with an error_code key. It does not throw.
    • Check the result for an error_code key even inside a try block.

Additional Resource Refer to Content Delivery API Errors for the full error code list.

Behavior

  • One call sends one Subsequent Sync request, GET /<apiVersion>/stacks/sync, with sync_token and the environment query parameter.
  • The API returns the entries and assets published, unpublished or deleted since the sync that issued the token. When the changes hold more than 100 records, the body has a pagination_token instead of a sync_token. Pass it to the paginationToken method for the next batch.
  • Store the sync_token of the last batch and pass it to syncToken on your next sync. You do not need to call sync again.
  • With the type arguments <contentstack.SyncResult, void>, syncToken returns a SyncResult, with the batch in items and the next token in paginationToken or syncToken. See Sync on the Stack class page for every field.
  • Known issue: With <contentstack.SyncResult, void>, an API rejection returns a SyncResult with every field null and no sign of the error. Call syncToken without type arguments when you need to read the error.

Example

Basic usage: fetch the changes since the last sync

import 'package:contentstack/contentstack.dart' as contentstack;

Future<void> main() async {
  final stack = contentstack.Stack('<API_KEY>', '<DELIVERY_TOKEN>', '<ENVIRONMENT>');

  try {
    final response = await stack.syncToken('<SYNC_TOKEN>');
    if (response is Map && response.containsKey('error_code')) {
      // The API rejected the request, for example because the token is invalid
      print('Request failed: ${response['error_code']} ${response['error_message']}');
    } else {
      for (final item in response['items']) {
        print('${item['type']} ${item['data']['uid']}');
      }
      print('next sync token: ${response['sync_token']}');
    }
  } catch (e) {
    // Thrown for a non-JSON response, a network failure or a 30-second timeout
    print('Request did not complete: $e');
  }
}

Typed result: read the next sync token from SyncResult

import 'package:contentstack/contentstack.dart' as contentstack;

Future<void> main() async {
  final stack = contentstack.Stack('<API_KEY>', '<DELIVERY_TOKEN>', '<ENVIRONMENT>');

  final result = await stack.syncToken<contentstack.SyncResult, void>('<SYNC_TOKEN>');
  print('changed items: ${result?.items?.length}');
  print('next sync token: ${result?.syncToken ?? result?.paginationToken}');
}