Asset

View as Markdown

Asset

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.

Assets are the media files uploaded to a stack, such as images, videos, PDFs and audio files. Asset reads one published asset by its UID. Use this class for the following tasks:

  • Fetch the details of one asset, such as its URL, file name and size.
  • Add the height and width of an image to the response.
  • Request a specific version of the asset.

stack.asset('<ASSET_UID>') returns an Asset. To list several assets, call stack.assetQuery(), which returns an AssetQuery.

Instance State

  • Pass an asset UID to stack.asset before you call fetch, for example stack.asset('<ASSET_UID>').
  • stack.asset(null) and stack.asset('') return an Asset without an error, and the setters such as includeDimension still store their values. fetch then throws Exception before it sends a request, because a single-asset request needs a UID in its path.

Warning Create an Asset with stack.asset, not with the Asset constructor. The constructor reads the HTTP client that Stack creates, and contentstack.Asset('<ASSET_UID>') has none, so the call throws a TypeError.

Class-Level Notes

What fetch sends.

  • One fetch call sends one Get a single asset request, GET /v3/assets/<ASSET_UID>. The version segment comes from the apiVersion you pass to Stack, 'v3' by default.
  • The setters store query parameters on the Asset. fetch sends every stored parameter, and the api_key, access_token and environment headers from the Stack.
  • stack.asset copies the stack's environment into the environment query parameter. The environment method replaces that query parameter for one Asset.

Branch scoping. When you pass branch to the Stack constructor, fetch sends it as the branch header, so the request reads the asset from that branch.

Settings stay on the instance.

  • Each setter writes a fixed value under a fixed query parameter key, and a second call on the same key replaces the first value.
  • No method removes a stored parameter. To fetch without one, create a new Asset with stack.asset.

AssetModel

fetch<contentstack.AssetModel, void>() returns an AssetModel instead of a Map. AssetModel.fromJson builds one from an asset map, and toJson() returns the map form. The model keeps the 14 fields in the table below and drops every other key in the response, such as _metadata or _branch. Read the untyped result when you need those keys.

PropertyTypeAccessDefaultDescription
uidString?Read and writenullAsset UID, from uid.
createdAtString?Read and writenullCreation time, from created_at.
updatedAtString?Read and writenullLast update time, from updated_at.
createdByString?Read and writenullUID of the user who created the asset, from created_by.
updatedByString?Read and writenullUID of the user who last updated the asset, from updated_by.
contentTypeString?Read and writenullFile type of the asset, such as image/png, from content_type.
fileSizeString?Read and writenullFile size in bytes, from file_size.
tagsList?Read and writenullTags on the asset, from tags.
filenameString?Read and writenullFile name, from filename.
urlString?Read and writenullDelivery URL of the file, from url.
versionint?Read and writenullAsset version number, from _version.
titleString?Read and writenullAsset title, from title.
dimensionMap<dynamic, dynamic>?Read and writenullImage height and width, from dimension, when you call includeDimension.
publishDetailsMap?Read and writenullEnvironment, locale and time of publishing, from publish_details.

A field is null when the response has no matching key.

Method Index

Method NameReturnsDescription
fetchThe requested asset.Sends the request and returns one asset.
environmentNothing. The asset keeps the setting for its next fetch.Sets the environment query parameter.
includeDimensionNothing. The asset keeps the setting for its next fetch.Adds the image height and width.
includeFallbackNothing. The asset keeps the setting for its next fetch.Requests fallback-locale details when a localization is missing.
versionNothing. The asset keeps the setting for its next fetch.Sets the asset version to request.

Class-Level Snippet

The snippet below fetches one image asset with its dimensions and prints its title, URL, height and width.

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>')..includeDimension();

  try {
    final response = await asset.fetch();
    if (response is Map && response.containsKey('error_code')) {
      // The API rejected the request
      print('Request failed: ${response['error_code']} ${response['error_message']}');
    } else {
      final image = response['asset'];
      print('${image['title']} ${image['url']}');
      print('${image['dimension']['height']} x ${image['dimension']['width']}');
    }
  } 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');
  }
}

Methods

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

environment

environment sets the environment query parameter that fetch sends for this asset.

NameTypeDescription
environment (required)String

Publishing environment to read the asset from.

Default: Not applicable

Returns: void. Nothing. The asset keeps the setting for its next fetch.

Validation

  • There is no client-side validation. environment stores any string, including an empty one.
  • An invalid value surfaces when fetch() sends the request. The API rejection comes back as the result, not as an exception. Check the result for an error_code key.

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

Behavior

  • Client-side only. environment replaces the environment query parameter that stack.asset copied from the Stack, and makes no request.
  • The change applies to this asset only. The environment header that the Stack sends on every request keeps the environment you passed to the Stack constructor.
  • The API expects a delivery token that belongs to the environment you read from. See the access_token header in Get a single asset. To read from a second environment, create a second Stack with that environment and its delivery token.
  • An empty string sends the environment query parameter with no value.

Example

Basic usage: fetch an asset from a named environment

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>')..environment('<ENVIRONMENT>');

  try {
    final response = await asset.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['asset']['publish_details']);
    }
  } 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');
  }
}

fetch

fetch sends the asset request, with every setting the asset holds, and returns the published asset.

This method takes no parameters. Its two type arguments, T and K, choose the result type: pass none for a Map, or <contentstack.AssetModel, void> for an AssetModel.

Returns: Future<T>. The requested asset.

Validation

  • Throws Exception when the asset holds a null or empty UID, because a single-asset request needs the UID in its path. fetch throws at the call, before it sends a request.
  • During the request, fetch throws only when the request does not complete: a response that is not JSON, a network failure, or a TimeoutException after 30 seconds.
    • An API rejection comes back as the result, not as an exception. The untyped result is a Map with error_code and error_message keys.
    • Check the result for an error_code key even inside a try block.

Known issue When the API rejects the request, fetch<contentstack.AssetModel, void>() returns an AssetModel with every field null and no error details. Call fetch() without type arguments when you need to check error_code.

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

Behavior

  • One call sends one Get a single asset request, GET /v3/assets/<ASSET_UID>, with every query parameter the setters stored and the headers of the Stack.
  • With no type arguments, fetch returns the decoded JSON body as a Map. Read the asset from response['asset'].
  • With <contentstack.AssetModel, void>, fetch returns the asset as an AssetModel. The model keeps 14 fields and drops every other key in the response. See the AssetModel table on the Asset class page.
  • The SDK declares the result as nullable (T?), so read a typed result with ?., as the second example below does.
  • Without a version, the API returns the latest published version of the asset.
  • Calling fetch twice sends two requests, because the SDK caches nothing.

Example

Basic usage: fetch an asset and print its URL

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
      print('Request failed: ${response['error_code']} ${response['error_message']}');
    } else {
      print('${response['asset']['filename']} ${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');
  }
}

Typed result: read the asset as an AssetModel

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

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

  final model = await stack.asset('<ASSET_UID>').fetch<contentstack.AssetModel, void>();
  print('${model?.title} ${model?.contentType} ${model?.fileSize}');
}

Edge case: an asset with no UID

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

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

  try {
    await stack.asset('').fetch();
  } on Exception catch (e) {
    // Thrown before any request, because the asset UID is empty
    print('No request sent: $e');
  }
}

includeDimension

includeDimension asks the API to add the height and width of the image to the asset in the response.

This method takes no parameters.

Returns: void. Nothing. The asset keeps the setting for its next fetch.

Validation

  • There is no client-side validation. includeDimension takes no input and cannot fail.
  • Errors that do occur come from the fetch() call that follows, not from includeDimension(). The API rejection comes back as the result, not as an exception. Check the result for an error_code key.

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

Behavior

  • Client-side only. includeDimension sets the include_dimension query parameter to 'true' and makes no request. The fetch() call that follows sends it.
  • The API returns the dimensions under the dimension key, with height and width, for JPG, GIF, PNG, WebP, BMP, TIFF, SVG and PSD images. See include_dimension in Get a single asset.
  • The typed AssetModel keeps the dimensions in its dimension field.
  • Calling includeDimension twice changes nothing, because both calls write the same value under the same key.

Example

Basic usage: print the height and width of an image

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>')..includeDimension();

  try {
    final response = await asset.fetch();
    if (response is Map && response.containsKey('error_code')) {
      // The API rejected the request
      print('Request failed: ${response['error_code']} ${response['error_message']}');
    } else {
      final dimension = response['asset']['dimension'];
      print('${dimension['height']} x ${dimension['width']}');
    }
  } 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');
  }
}

Typed result: read the dimensions from an AssetModel

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>')..includeDimension();

  final model = await asset.fetch<contentstack.AssetModel, void>();
  print(model?.dimension);
}

includeFallback

includeFallback asks the API to return the asset details published in the fallback locale when the requested locale has none.

This method takes no parameters.

Returns: void. Nothing. The asset keeps the setting for its next fetch.

Validation

  • There is no client-side validation. includeFallback takes no input and cannot fail.
  • Errors that do occur come from the fetch() call that follows, not from includeFallback(). The API rejection comes back as the result, not as an exception. Check the result for an error_code key.

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

Behavior

  • Client-side only. includeFallback sets the include_fallback query parameter to 'true' and makes no request. The fetch() call that follows sends it.
  • The API includes the published asset details from the fallback locale when the specified locale has no published content. See include_fallback in Get a single asset.
  • Asset has no method that sets a locale, and the Get a single asset reference lists no locale query parameter.
  • Calling includeFallback twice changes nothing, because both calls write the same value under the same key.

Example

Basic usage: fetch an asset with fallback-locale details

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>')..includeFallback();

  try {
    final response = await asset.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['asset']['title']} ${response['asset']['publish_details']}');
    }
  } 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');
  }
}

version

version sets the version number of the asset that fetch requests.

NameTypeDescription
version (required)int

Version number of the asset to fetch.

Default: Not applicable

Returns: void. Nothing. The asset keeps the setting for its next fetch.

Validation

  • There is no client-side validation. version stores any integer as a string, including 0 and negative numbers.
  • An invalid value surfaces when fetch() sends the request. The API rejection comes back as the result, not as an exception. Check the result for an error_code key.

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

Behavior

  • Client-side only. version sets the version query parameter and makes no request. The fetch() call that follows sends it.
  • Without version, the API returns the latest published version of the asset. See version in Get a single asset.
  • A second call replaces the first value, because both calls write the same key.

Note The Get a single asset reference says to keep the environment parameter blank to retrieve a specific version. stack.asset always sets the environment query parameter, and the Stack sends an environment header on every request. The environment method with an empty string sends the query parameter with no value.

Example

Basic usage: fetch version 2 of an 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>')..version(2);

  try {
    final response = await asset.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['asset']['title']} version ${response['asset']['_version']}');
    }
  } 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');
  }
}