Query
Query
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.
Query builds a request for the published entries of one content type. Use this class to
- match entries by field value, by a field of a referenced entry, or by a combination of conditions
- choose the locale and the references that the response carries
- sort and paginate the result
- send the request with the find method
stack.contentType('<CONTENT_TYPE_UID>').entry().query() creates a query. query() takes no arguments, and the query reads its content type UID from the stack.contentType() call before it. The table below describes that argument:
| Name | Type | Description |
|---|---|---|
| contentTypeId | String? | UID of the content type whose entries the query reads. Pass it to stack.contentType(). |
- entry().query() throws if you called stack.contentType() without a UID, because a query reads the entries of one content type.
- Every method except find and getQueryUrl returns void. Chain the setters on one query with the cascade operator .., then call find() on that query.
Warning stack.contentType('').entry().query() does not throw. The query builds the request path /content_types//entries. Check that a UID variable is non-empty before you pass it.
Class-Level Notes
Imports for the filter types.
- The package library does not export the types that where, operator and whereReference take. Import each one from its src/ path, as the six lines below show. The Dart analyzer reports them as implementation imports, and no other import path exists.
import 'package:contentstack/src/enums/operations.dart'; import 'package:contentstack/src/enums/operations_type.dart'; import 'package:contentstack/src/enums/operator.dart'; import 'package:contentstack/src/enums/operator_type.dart'; import 'package:contentstack/src/enums/reference.dart'; import 'package:contentstack/src/enums/reference_type.dart';
Two stores, merged when the request goes out.
- where, query, addQuery, operator and whereReference write the condition object. find encodes it as JSON and sends it as the query URL parameter.
- Every other setter writes a URL parameter directly, such as limit, locale or include[].
- When the query contains any condition, find writes the query key last, so it replaces a query value from param, addParam or addParams.
- A second value for the same key replaces the first. No method removes a value. Create a new query to send a request without it.
Headers belong to the stack.
- setHeader and removeHeader change the header map of the stack that created the query. The change reaches every later request from that stack, not only this query.
Pagination.
- Each find call sends one request and returns one page. Without limit, the API returns the first 100 entries.
- Query has no method for the total count. Call param with param('include_count', 'true') and read the count key, then use skip and limit to read later pages. See the Pagination request.
Capability Matrix
| Capability | Supported | Notes / Alternative |
|---|---|---|
| Typed results with find<List<EntryModel>, EntryModel>() | No | Call find() without type arguments and build each model with contentstack.EntryModel.fromJson. See find. |
| Queries on a Stack created with a livePreview map | No | find() returns null. Run queries from a second Stack created without livePreview. |
| Keep or drop several top-level fields with only or except | No | Pass one field through addParam, or read the fields you need from the full response. |
| Resolve several reference fields by UID | No | includeReference holds one field. Call param('include_all', 'true') to resolve every reference field. |
| Two operators on one field through where | No | Pass both operators in one map to addQuery. |
| Return every entry in one call | No | Read the entries one page at a time with skip and limit. |
| Automatic retry on 429 | No | Implement backoff in your calling code. |
Filter Types
where, operator and whereReference each take an object that you build from a class and an enum. Each constructor takes positional arguments and keeps them as final fields of the same names. The table below lists the three classes:
| Class | Constructor | Values of the enum | Used by |
|---|---|---|---|
| QueryOperation | QueryOperation(QueryOperationType operationType, dynamic value) | Equals, NotEquals, Includes, Excludes, IsLessThan, IsLessThanOrEqual, IsGreaterThan, IsGreaterThanOrEqual, Exists, Matches | where |
| QueryOperator | QueryOperator(QueryOperatorType operatorType, List<Query> queryObjects) | And, Or | operator |
| QueryReference | QueryReference(QueryReferenceType referenceType, Query query) | Include, NotInclude | whereReference |
The page of each method lists the operator that each enum value sends.
Method Index
Every method below works on any Query. The groups follow what you are trying to do.
Filter the entries. Available on any Query, before find.
| Method Name | Returns | Description |
|---|---|---|
| where | Nothing. The query keeps the setting for its next request. | Matches entries by a field value and an operator. |
| query | Nothing. The query keeps the setting for its next request. | Matches entries whose field equals a string. |
| addQuery | Nothing. The query keeps the setting for its next request. | Merges your own conditions into the query. |
| operator | Nothing. The query keeps the setting for its next request. | Joins the conditions of other queries with $and or $or. |
| whereReference | Nothing. The query keeps the setting for its next request. | Matches entries by a field of a referenced entry. |
Choose the locale. Available on any Query, before find.
| Method Name | Returns | Description |
|---|---|---|
| locale | Nothing. The query keeps the setting for its next request. | Sets the locale to read. |
| includeFallback | Nothing. The query keeps the setting for its next request. | Returns fallback locale content for unpublished localizations. |
Shape the response. Available on any Query, before find.
| Method Name | Returns | Description |
|---|---|---|
| only | Nothing. The query keeps the setting for its next request. | Keeps the listed top-level fields. |
| except | Nothing. The query keeps the setting for its next request. | Leaves the listed top-level fields out. |
| includeReference | Nothing. The query keeps the setting for its next request. | Returns referenced entries in full instead of as UIDs. |
| includeReferenceContentTypeUID | Nothing. The query keeps the setting for its next request. | Adds the content type UID to each referenced entry. |
| includeContentType | Nothing. The query keeps the setting for its next request. | Returns the content type schema with the entries. |
| includeEmbeddedItems | Nothing. The query keeps the setting for its next request. | Returns items embedded in Rich Text Editor fields. |
| includeBranch | Nothing. The query keeps the setting for its next request. | Adds the _branch key to each entry. |
Sort and paginate. Available on any Query, before find.
| Method Name | Returns | Description |
|---|---|---|
| limit | Nothing. The query keeps the setting for its next request. | Sets the maximum number of entries returned. |
| skip | Nothing. The query keeps the setting for its next request. | Leaves out a number of entries before the page starts. |
| orderByAscending | Nothing. The query keeps the setting for its next request. | Sorts entries by one field, lowest first. |
| orderByDescending | Nothing. The query keeps the setting for its next request. | Sorts entries by one field, highest first. |
Send a parameter the SDK has no method for. Available on any Query, before find.
| Method Name | Returns | Description |
|---|---|---|
| param | Nothing. The query keeps the setting for its next request. | Adds one URL parameter. |
| addParam | Nothing. The query keeps the setting for its next request. | Adds one URL parameter, the same as param. |
| addParams | Nothing. The query keeps the setting for its next request. | Adds several URL parameters from a map. |
Change the request headers. Available on any Query. The change applies to every request from the stack.
| Method Name | Returns | Description |
|---|---|---|
| setHeader | Nothing. The stack uses the change on its next request. | Adds or replaces a header. |
| removeHeader | Nothing. The stack uses the change on its next request. | Deletes a header. |
Send or inspect the request. Available on any Query, as the last call in the chain.
| Method Name | Returns | Description |
|---|---|---|
| find | The matching entries. | Sends the query and returns one page of entries. |
| getQueryUrl | The URL parameters of the next request. | Returns the parameters without sending a request. |
Class-Level Snippet
The following snippet lists the ten cheapest entries under a price in one locale, with the total number of matches.
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>');
final query = stack.contentType('<CONTENT_TYPE_UID>').entry().query()
..where('price_in_usd', QueryOperation(QueryOperationType.IsLessThan, 600))
..locale('<LOCALE>')
..includeFallback()
..orderByAscending('price_in_usd')
..limit(10)
..param('include_count', 'true');
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 {
print('Total matches: ${response['count']}');
for (final entry in response['entries']) {
print('${entry['title']}: ${entry['price_in_usd']}');
}
}
} 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 Query class has its own section below, with its parameters, validation rules, behavior, and examples.
addParam
addParam adds one URL parameter to the request that the find method sends.
| Name | Type | Description |
|---|---|---|
| key (required) | String | Name of the URL parameter. |
| value (required) | String | Value of the URL parameter. |
Returns: void. Nothing. The query keeps the setting for its next request.
Validation
- addParam ignores the call when key or value is an empty string. It throws nothing, so the parameter is missing from the request with no sign in your code.
- The SDK does not check the parameter name against the API. An unknown name or an invalid value surfaces when find() 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. addParam writes one key to the URL parameters of the query and makes no request.
- On a query, addParam and the param method do the same thing. The addParams method writes several keys in one call.
- A second call with the same key replaces the value. That includes keys that other methods write, such as limit, locale and environment.
- addParam is the workaround for the only and except methods, which send a list in a form that the API does not read. Pass one field, for example addParam('only[BASE][]', 'title'). See the Only operator request.
Example
Basic usage: add the metadata of each entry to the response
import 'package:contentstack/contentstack.dart' as contentstack;
Future<void> main() async {
final stack = contentstack.Stack('<API_KEY>', '<DELIVERY_TOKEN>', '<ENVIRONMENT>');
final query = stack.contentType('<CONTENT_TYPE_UID>').entry().query()
..addParam('include_metadata', 'true');
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 entry in response['entries']) {
print(entry['_metadata']);
}
}
} catch (e) {
// Thrown for a non-JSON response, a network failure or a 30-second timeout
print('Request did not complete: $e');
}
}Projection: keep one top-level field in each entry
import 'package:contentstack/contentstack.dart' as contentstack;
Future<void> main() async {
final stack = contentstack.Stack('<API_KEY>', '<DELIVERY_TOKEN>', '<ENVIRONMENT>');
final query = stack.contentType('<CONTENT_TYPE_UID>').entry().query()
..addParam('only[BASE][]', 'title');
final response = await query.find();
print(response['entries']);
}addParams
addParams adds several URL parameters to the request that the find method sends, in one call.
| Name | Type | Description |
|---|---|---|
| parameters (required) | Map | URL parameter names mapped to string values. |
Returns: void. Nothing. The query keeps the setting for its next request.
Validation
- addParams ignores an empty map.
- Every key and value must be a String. addParams throws TypeError at the call for any other type, such as an int or a bool, because the query stores URL parameters as strings. Write '5' and 'true', not 5 and true.
- The SDK does not check the parameter names against the API. An unknown name or an invalid value surfaces when find() 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. addParams copies each entry of the map into the URL parameters of the query and makes no request.
- A key that the query already holds takes the new value. That includes keys that other methods write, such as limit, locale and environment.
- Unlike the param method, addParams accepts an empty string as a value and sends it.
- If the query contains a where condition or a related one, the find method writes the conditions under query and replaces your value. Do not pass query as a key.
Example
Basic usage: request the count and fallback content in one call
import 'package:contentstack/contentstack.dart' as contentstack;
Future<void> main() async {
final stack = contentstack.Stack('<API_KEY>', '<DELIVERY_TOKEN>', '<ENVIRONMENT>');
final query = stack.contentType('<CONTENT_TYPE_UID>').entry().query()
..addParams({
'locale': '<LOCALE>',
'include_fallback': 'true',
'include_count': 'true',
});
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 {
print('Total entries: ${response['count']}');
}
} catch (e) {
// Thrown for a non-JSON response, a network failure or a 30-second timeout
print('Request did not complete: $e');
}
}addQuery
addQuery merges your own conditions into the condition object of the query.
| Name | Type | Description |
|---|---|---|
| parameters (required) | Map | Field UIDs or operators mapped to conditions. |
Returns: void. Nothing. The query keeps the setting for its next request.
Validation
- addQuery ignores an empty map.
- addQuery throws TypeError at the call for a key that is not a String, because the condition object accepts string keys only.
- There is no check on the values. A value that JSON cannot encode, such as a DateTime, makes the find method throw JsonUnsupportedObjectError.
- An invalid condition surfaces when find() 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. addQuery copies each entry of the map into the condition object of the query and makes no request. The find method encodes that object as JSON and sends it as the query URL parameter.
- Use addQuery for a condition that the where method cannot build, such as two operators on one field or a raw $or list. Write the map in the JSON shape that the API reference shows, for example the OR Operator request.
- In a Dart string, escape the dollar sign of an operator ('\$gte'), or Dart reads it as string interpolation.
- A key that the condition object already holds takes the new value, whichever method wrote it.
Example
Basic usage: match a price range with two operators on one field
import 'package:contentstack/contentstack.dart' as contentstack;
Future<void> main() async {
final stack = contentstack.Stack('<API_KEY>', '<DELIVERY_TOKEN>', '<ENVIRONMENT>');
final query = stack.contentType('<CONTENT_TYPE_UID>').entry().query()
..addQuery({
'price_in_usd': {'\$gte': 100, '\$lte': 500},
});
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 entry in response['entries']) {
print('${entry['title']}: ${entry['price_in_usd']}');
}
}
} catch (e) {
// Thrown for a non-JSON response, a network failure or a 30-second timeout
print('Request did not complete: $e');
}
}Raw operator: match entries whose color is Gold or Black
import 'package:contentstack/contentstack.dart' as contentstack;
Future<void> main() async {
final stack = contentstack.Stack('<API_KEY>', '<DELIVERY_TOKEN>', '<ENVIRONMENT>');
final query = stack.contentType('<CONTENT_TYPE_UID>').entry().query()
..addQuery({
'\$or': [
{'color': 'Gold'},
{'color': 'Black'},
],
});
final response = await query.find();
print(response['entries']);
}except
except asks the API to leave the listed top-level fields out of each entry.
| Name | Type | Description |
|---|---|---|
| fieldUid (required) | List<String> | UIDs of the top-level fields to leave out. |
Returns: void. Nothing. The query keeps the setting for its next request.
Validation
- except ignores an empty list. It does not check the field UIDs.
- An invalid value surfaces when find() 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. except writes the except[BASE][] URL parameter and makes no request. The find method sends it. See the Exclude operator request.
- BASE stands for the top-level fields of the entry. To leave out fields of a referenced entry instead, see the includeReference method.
- A second call replaces the first list.
Known issue except sends the whole list as one value in the form [description, tags], not one except[BASE][] value per field, so the API does not apply your field list. To leave out one field, call addParam with addParam('except[BASE][]', 'description'). To leave out several, ignore the fields you do not need in the full response.
Example
Basic usage: pass the fields to leave out
import 'package:contentstack/contentstack.dart' as contentstack;
Future<void> main() async {
final stack = contentstack.Stack('<API_KEY>', '<DELIVERY_TOKEN>', '<ENVIRONMENT>');
// The SDK sends this list as one value. See the Known issue above.
final query = stack.contentType('<CONTENT_TYPE_UID>').entry().query()
..except(['description', 'tags']);
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 entry in response['entries']) {
print(entry.keys);
}
}
} catch (e) {
// Thrown for a non-JSON response, a network failure or a 30-second timeout
print('Request did not complete: $e');
}
}Workaround: leave out one field with addParam
import 'package:contentstack/contentstack.dart' as contentstack;
Future<void> main() async {
final stack = contentstack.Stack('<API_KEY>', '<DELIVERY_TOKEN>', '<ENVIRONMENT>');
final query = stack.contentType('<CONTENT_TYPE_UID>').entry().query()
..addParam('except[BASE][]', 'description');
final response = await query.find();
for (final entry in response['entries']) {
print(entry.keys);
}
}find
find sends the query and returns one page of matching entries.
This method takes no parameters. It reads the content type UID and every setting from the query.
Returns: Future<T>. The matching entries.
Validation
- find does not check the query. The content type UID comes from stack.contentType(), and an empty UID builds the path /content_types//entries.
- find throws JsonUnsupportedObjectError if a condition holds a value that JSON cannot encode, such as a DateTime, because find encodes the conditions as JSON before the request.
- When the livePreview map of the stack holds enable: true, find throws ArgumentError if the map has no content_type_uid key.
- Beyond those cases, find throws only for a network failure, a 30-second timeout, or a response body that is not JSON.
- An API rejection returns as a normal result with an error_code key. It does not throw an exception.
- 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
- Each call sends one GET /content_types/{content_type_uid}/entries request with the headers of the stack. See the Get all entries request.
- Call find() without type arguments. It returns the response body as a Map, or null in the Live Preview case below. Read the entries from its entries key, and the total from its count key when you sent include_count.
- find builds the query string from two parts:
- The getQueryUrl method returns the same parameters without sending a request.
- find returns one page. Without limit, the API returns the first 100 entries. Use skip and limit to read later pages. See the Pagination request.
- The query keeps every setting, so a second find on the same query sends the same request again.
Known issue The typed form find<List<EntryModel>, EntryModel>() throws TypeError for every response. Call find() without type arguments, and build each model with contentstack.EntryModel.fromJson from the items of response['entries'], as the second example below shows.
Known issue When you create the Stack with any livePreview map, find() returns null instead of the entries. Run queries from a second Stack created without livePreview.
Example
Basic usage: list the entries 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 query = stack.contentType('<CONTENT_TYPE_UID>').entry().query();
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 entry in response['entries']) {
print(entry['title']);
}
}
} catch (e) {
// Thrown for a non-JSON response, a network failure or a 30-second timeout
print('Request did not complete: $e');
}
}Models: turn each entry into an EntryModel
import 'package:contentstack/contentstack.dart' as contentstack;
Future<void> main() async {
final stack = contentstack.Stack('<API_KEY>', '<DELIVERY_TOKEN>', '<ENVIRONMENT>');
final query = stack.contentType('<CONTENT_TYPE_UID>').entry().query()..limit(10);
final response = await query.find();
final models = (response['entries'] as List)
.map((item) => contentstack.EntryModel.fromJson(item as Map<String, dynamic>))
.toList();
for (final model in models) {
print('${model.uid}: ${model.title}');
}
}getQueryUrl
getQueryUrl returns the URL parameters that the next find call sends, without sending a request.
This method takes no parameters.
Returns: Map. The URL parameters of the next request.
Validation
- There is no client-side validation.
- getQueryUrl throws JsonUnsupportedObjectError if a condition holds a value that JSON cannot encode, such as a DateTime, because it encodes the conditions as JSON.
Behavior
- Client-side only. getQueryUrl makes no request.
- Despite its name, getQueryUrl returns a map of parameter names to values, not a URL. The map holds the environment parameter, every value from the setters, and the conditions as JSON text under the query key when there are any.
- The map has no host, path or headers.
- getQueryUrl returns the map that the query holds, not a copy. It writes the query key into that map before it returns, and a change that you make to the map reaches the next request.
Example
Basic usage: print the parameters before you send the query
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>');
final query = stack.contentType('<CONTENT_TYPE_UID>').entry().query()
..where('title', QueryOperation(QueryOperationType.Equals, 'Redmi 3S'))
..limit(5);
// Prints {environment: <ENVIRONMENT>, limit: 5, query: {"title":"Redmi 3S"}}
print(query.getQueryUrl());
}includeBranch
includeBranch asks the API to add the _branch key, the UID of the branch that holds the entry, to each entry.
This method takes no parameters.
Returns: void. Nothing. The query keeps the setting for its next request.
Validation
- There is no client-side validation.
- An invalid value surfaces when find() 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. includeBranch writes include_branch=true to the URL parameters and makes no request. The find method sends it. See the Get all entries request.
- includeBranch does not choose a branch. The branch argument of the Stack constructor, or the setHeader method, sets the branch that the request reads.
- No method removes the flag. Create a new query to send a request without it.
Example
Basic usage: show the branch of each entry
import 'package:contentstack/contentstack.dart' as contentstack;
Future<void> main() async {
final stack = contentstack.Stack('<API_KEY>', '<DELIVERY_TOKEN>', '<ENVIRONMENT>');
final query = stack.contentType('<CONTENT_TYPE_UID>').entry().query()..includeBranch();
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 entry in response['entries']) {
print('${entry['title']}: ${entry['_branch']}');
}
}
} catch (e) {
// Thrown for a non-JSON response, a network failure or a 30-second timeout
print('Request did not complete: $e');
}
}includeContentType
includeContentType asks the API to return the schema of the content type, including the schema of its Global fields, along with the entries.
This method takes no parameters.
Returns: void. Nothing. The query keeps the setting for its next request.
Validation
- There is no client-side validation.
- An invalid value surfaces when find() 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. includeContentType writes two URL parameters, include_content_type=true and include_global_field_schema=true, and makes no request. The find method sends them.
- The include_global_field_schema parameter returns the schema of each Global field in the content type. See the Get a single content type request.
- To read the schema without the entries, use the fetch method of the ContentType class.
- No method removes the flags. Create a new query to send a request without them.
Example
Basic usage: read the entries with their content type
import 'package:contentstack/contentstack.dart' as contentstack;
Future<void> main() async {
final stack = contentstack.Stack('<API_KEY>', '<DELIVERY_TOKEN>', '<ENVIRONMENT>');
final query = stack.contentType('<CONTENT_TYPE_UID>').entry().query()
..includeContentType();
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 {
// The response carries the content type next to the entries
print(response.keys);
}
} catch (e) {
// Thrown for a non-JSON response, a network failure or a 30-second timeout
print('Request did not complete: $e');
}
}includeEmbeddedItems
includeEmbeddedItems asks the API to return the entries and assets embedded in the Rich Text Editor fields of each entry.
This method takes no parameters.
Returns: void. Nothing. The query keeps the setting for its next request.
Validation
- There is no client-side validation.
- An invalid value surfaces when find() 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. includeEmbeddedItems writes include_embedded_items[]=BASE to the URL parameters and makes no request. The find method sends it.
- BASE returns the first level of embedded items, under the _embedded_items key. See the Get information on embedded RTE objects request.
- To also return items embedded inside those items, call addParam with addParam('include_embedded_items[]', 'RECURSIVE') instead. It writes the same key and replaces BASE. Add embedded_items_depth to set the number of levels. The API caps it at 5.
- No method removes the flag. Create a new query to send a request without it.
Example
Basic usage: read the embedded items of each entry
import 'package:contentstack/contentstack.dart' as contentstack;
Future<void> main() async {
final stack = contentstack.Stack('<API_KEY>', '<DELIVERY_TOKEN>', '<ENVIRONMENT>');
final query = stack.contentType('<CONTENT_TYPE_UID>').entry().query()
..includeEmbeddedItems();
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 entry in response['entries']) {
print(entry['_embedded_items']);
}
}
} catch (e) {
// Thrown for a non-JSON response, a network failure or a 30-second timeout
print('Request did not complete: $e');
}
}Nested items: read embedded items three levels deep
import 'package:contentstack/contentstack.dart' as contentstack;
Future<void> main() async {
final stack = contentstack.Stack('<API_KEY>', '<DELIVERY_TOKEN>', '<ENVIRONMENT>');
final query = stack.contentType('<CONTENT_TYPE_UID>').entry().query()
..addParam('include_embedded_items[]', 'RECURSIVE')
..addParam('embedded_items_depth', '3');
final response = await query.find();
print(response['entries']);
}includeFallback
includeFallback asks the API to return content from the fallback locale for entries that have no published content in the requested locale.
This method takes no parameters.
Returns: void. Nothing. The query keeps the setting for its next request.
Validation
- There is no client-side validation.
- An invalid value surfaces when find() 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. includeFallback writes include_fallback=true to the URL parameters and makes no request. The find method sends it. See the Get all entries request.
- Use it with the locale method, which sets the requested locale.
- No method removes the flag. Create a new query to send a request without it.
Example
Basic usage: read the entries of one locale with fallback content
import 'package:contentstack/contentstack.dart' as contentstack;
Future<void> main() async {
final stack = contentstack.Stack('<API_KEY>', '<DELIVERY_TOKEN>', '<ENVIRONMENT>');
final query = stack.contentType('<CONTENT_TYPE_UID>').entry().query()
..locale('<LOCALE>')
..includeFallback();
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 entry in response['entries']) {
print('${entry['title']} (${entry['locale']})');
}
}
} catch (e) {
// Thrown for a non-JSON response, a network failure or a 30-second timeout
print('Request did not complete: $e');
}
}includeReference
includeReference asks the API to return the entries that a reference field points to in full, instead of their UIDs only.
| Name | Type | Description |
|---|---|---|
| referenceFieldUid (required) | String | UID of the reference field to resolve. |
| includeReferenceField | IncludeClass? (named) | Field projection for the referenced entries. null returns every field. |
Returns: void. Nothing. The query keeps the setting for its next request.
Validation
- includeReference ignores the call when referenceFieldUid is an empty string. It does not check the field UIDs.
- An invalid value surfaces when find() 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. includeReference writes the include[] URL parameter, and the only or except parameter for a projection, and makes no request. The find method sends them. See the Include Reference request.
- For a reference field inside a Group field, pass the path with a dot, for example bank_offers.bank. See the Include Reference Within Group request.
- Build includeReferenceField with contentstack.IncludeClass(contentstack.IncludeType.Only, ['title']). The package library exports both types. The Entry class page describes them. The table below lists what the query sends for each form:
| includeReferenceField | What the query sends |
|---|---|
| Omitted | include[]=author |
| IncludeType.None with a field list | include[]=[author, category], one value |
| IncludeType.Only with a field list | include[]=author and only={author: [title]} |
| IncludeType.Except with a field list | include[]=author and except={author: [title]} |
- The query holds one reference field. A second call replaces the first. To resolve every reference field of the entries, call param with param('include_all', 'true'), which returns referenced entries to a depth of 1. See the Include all references request.
Known issue With IncludeType.None, the SDK sends every UID as one value ([author, category]), so the API does not resolve the references. Call includeReference without includeReferenceField instead. With IncludeType.Only or IncludeType.Except, the SDK sends the field list as only={author: [title]}, not the only[author][]=title form that the API documents, so the API does not apply the list. Call includeReference('author'), then addParam with addParam('only[author][]', 'title') to keep one field.
Example
Basic usage: resolve the author reference of each entry
import 'package:contentstack/contentstack.dart' as contentstack;
Future<void> main() async {
final stack = contentstack.Stack('<API_KEY>', '<DELIVERY_TOKEN>', '<ENVIRONMENT>');
final query = stack.contentType('<CONTENT_TYPE_UID>').entry().query()
..includeReference('author');
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 entry in response['entries']) {
print(entry['author']);
}
}
} catch (e) {
// Thrown for a non-JSON response, a network failure or a 30-second timeout
print('Request did not complete: $e');
}
}Projection: pass a field list for the referenced entries
import 'package:contentstack/contentstack.dart' as contentstack;
Future<void> main() async {
final stack = contentstack.Stack('<API_KEY>', '<DELIVERY_TOKEN>', '<ENVIRONMENT>');
// The SDK sends the field list in a form that the API does not apply. See the Known issue above.
final query = stack.contentType('<CONTENT_TYPE_UID>').entry().query()
..includeReference(
'author',
includeReferenceField: contentstack.IncludeClass(contentstack.IncludeType.Only, ['title']),
);
final response = await query.find();
print(response['entries']);
}Workaround: keep one field of the referenced entries
import 'package:contentstack/contentstack.dart' as contentstack;
Future<void> main() async {
final stack = contentstack.Stack('<API_KEY>', '<DELIVERY_TOKEN>', '<ENVIRONMENT>');
final query = stack.contentType('<CONTENT_TYPE_UID>').entry().query()
..includeReference('author')
..addParam('only[author][]', 'title');
final response = await query.find();
for (final entry in response['entries']) {
print(entry['author']);
}
}includeReferenceContentTypeUID
includeReferenceContentTypeUID asks the API to add the content type UID to each referenced entry in the response.
This method takes no parameters.
Returns: void. Nothing. The query keeps the setting for its next request.
Validation
- There is no client-side validation.
- An invalid value surfaces when find() 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. includeReferenceContentTypeUID writes include_reference_content_type_uid=true to the URL parameters and makes no request. The find method sends it.
- Use it with the includeReference method. It tells you which content type each referenced entry belongs to when a reference field points to more than one content type.
- No method removes the flag. Create a new query to send a request without it.
Example
Basic usage: resolve a reference and show the content type of each referenced entry
import 'package:contentstack/contentstack.dart' as contentstack;
Future<void> main() async {
final stack = contentstack.Stack('<API_KEY>', '<DELIVERY_TOKEN>', '<ENVIRONMENT>');
final query = stack.contentType('<CONTENT_TYPE_UID>').entry().query()
..includeReference('author')
..includeReferenceContentTypeUID();
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 entry in response['entries']) {
print(entry['author']);
}
}
} catch (e) {
// Thrown for a non-JSON response, a network failure or a 30-second timeout
print('Request did not complete: $e');
}
}limit
limit sets the maximum number of entries that the find method returns.
| Name | Type | Description |
|---|---|---|
| limitCount (required) | int | Maximum number of entries in the response. |
Returns: void. Nothing. The query keeps the setting for its next request.
Validation
- There is no client-side validation. limit converts the number to a string, so zero or a negative number reaches the request unchanged.
- The API accepts positive integers only. For limit=0 or a non-numeric value, it returns the default number of entries rather than every entry. See the Limit request.
- An invalid value surfaces when find() 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. limit writes the limit URL parameter and makes no request. The find method sends it.
- Without limit, the API returns the first 100 entries. See the Pagination request.
- A second call replaces the first value.
- The param, addParam and addParams methods write to the same URL parameters. A limit key from any of them replaces the value from limit, and the reverse.
Example
Basic usage: read at most five entries
import 'package:contentstack/contentstack.dart' as contentstack;
Future<void> main() async {
final stack = contentstack.Stack('<API_KEY>', '<DELIVERY_TOKEN>', '<ENVIRONMENT>');
final query = stack.contentType('<CONTENT_TYPE_UID>').entry().query()..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 entry in response['entries']) {
print(entry['title']);
}
}
} catch (e) {
// Thrown for a non-JSON response, a network failure or a 30-second timeout
print('Request did not complete: $e');
}
}Pagination: read the second page of ten entries
import 'package:contentstack/contentstack.dart' as contentstack;
Future<void> main() async {
final stack = contentstack.Stack('<API_KEY>', '<DELIVERY_TOKEN>', '<ENVIRONMENT>');
final query = stack.contentType('<CONTENT_TYPE_UID>').entry().query()
..limit(10)
..skip(10);
final response = await query.find();
print(response['entries']);
}locale
locale sets the language of the entries that the find method returns.
| Name | Type | Description |
|---|---|---|
| locale (required) | String | Locale code to read, for example fr-fr. |
Returns: void. Nothing. The query keeps the setting for its next request.
Validation
- There is no client-side validation. An empty string reaches the request as locale=.
- An invalid value surfaces when find() 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. locale writes the locale URL parameter and makes no request. The find method sends it.
- The API returns only the entries published in that locale. See the Get all entries request.
- Add the includeFallback method to return fallback content for entries that have no published content in the locale.
- A second call replaces the first value.
Example
Basic usage: read the entries of one locale
import 'package:contentstack/contentstack.dart' as contentstack;
Future<void> main() async {
final stack = contentstack.Stack('<API_KEY>', '<DELIVERY_TOKEN>', '<ENVIRONMENT>');
final query = stack.contentType('<CONTENT_TYPE_UID>').entry().query()..locale('<LOCALE>');
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 entry in response['entries']) {
print('${entry['title']} (${entry['locale']})');
}
}
} catch (e) {
// Thrown for a non-JSON response, a network failure or a 30-second timeout
print('Request did not complete: $e');
}
}only
only asks the API to return only the listed top-level fields of each entry.
| Name | Type | Description |
|---|---|---|
| fieldUid (required) | List<String> | UIDs of the top-level fields to keep. |
Returns: void. Nothing. The query keeps the setting for its next request.
Validation
- only ignores an empty list. It does not check the field UIDs.
- An invalid value surfaces when find() 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. only writes the only[BASE][] URL parameter and makes no request. The find method sends it. See the Only operator request.
- BASE stands for the top-level fields of the entry. To keep fields of a referenced entry instead, see the includeReference method.
- A second call replaces the first list.
Known issue only sends the whole list as one value in the form [title, url], not one only[BASE][] value per field, so the API does not apply your field list. To keep one field, call addParam with addParam('only[BASE][]', 'title'). To keep several, read the fields you need from the full response.
Example
Basic usage: pass the fields to keep
import 'package:contentstack/contentstack.dart' as contentstack;
Future<void> main() async {
final stack = contentstack.Stack('<API_KEY>', '<DELIVERY_TOKEN>', '<ENVIRONMENT>');
// The SDK sends this list as one value. See the Known issue above.
final query = stack.contentType('<CONTENT_TYPE_UID>').entry().query()
..only(['title', 'url']);
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 entry in response['entries']) {
print(entry);
}
}
} catch (e) {
// Thrown for a non-JSON response, a network failure or a 30-second timeout
print('Request did not complete: $e');
}
}Workaround: keep one field with addParam
import 'package:contentstack/contentstack.dart' as contentstack;
Future<void> main() async {
final stack = contentstack.Stack('<API_KEY>', '<DELIVERY_TOKEN>', '<ENVIRONMENT>');
final query = stack.contentType('<CONTENT_TYPE_UID>').entry().query()
..addParam('only[BASE][]', 'title');
final response = await query.find();
for (final entry in response['entries']) {
print(entry['title']);
}
}operator
operator joins the conditions of several queries with $and or $or.
| Name | Type | Description |
|---|---|---|
| operator (required) | QueryOperator | Join type and the queries whose conditions it joins. |
Returns: void. Nothing. The query keeps the setting for its next request.
Validation
- There is no client-side validation. operator ignores a QueryOperator whose list of queries is empty.
- An invalid condition in a joined query surfaces when find() 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.
Example
Behavior
- Client-side only. operator writes a $and or $or key to the condition object of the query and makes no request. The find method sends it in the query URL parameter. See the AND Operator and OR Operator requests.
- Import QueryOperator and QueryOperatorType from src/, because the package library does not export them. Add the following two import lines:
import 'package:contentstack/src/enums/operator.dart'; import 'package:contentstack/src/enums/operator_type.dart';
- Build the operator with two positional arguments: QueryOperator(QueryOperatorType.Or, [firstQuery, secondQuery]). QueryOperatorType has two values, And and Or.
- operator reads only the conditions of each joined query, the ones that the where, query, addQuery and whereReference methods wrote. It ignores their URL parameters, such as limit or locale. Set those on the query that calls find.
- The query keeps a reference to each joined query, not a copy. A condition that you add to a joined query after operator still reaches the next find call.
- A second operator call with the same type replaces the first list. An And call and an Or call write different keys, so both reach the request.
- Conditions that the outer query holds from where sit next to the $and or $or key in the same condition object.
Basic usage: match entries that are Gold or cost less than 600
import 'package:contentstack/contentstack.dart' as contentstack;
import 'package:contentstack/src/enums/operations.dart';
import 'package:contentstack/src/enums/operations_type.dart';
import 'package:contentstack/src/enums/operator.dart';
import 'package:contentstack/src/enums/operator_type.dart';
Future<void> main() async {
final stack = contentstack.Stack('<API_KEY>', '<DELIVERY_TOKEN>', '<ENVIRONMENT>');
final contentType = stack.contentType('<CONTENT_TYPE_UID>');
final gold = contentType.entry().query()
..where('color', QueryOperation(QueryOperationType.Equals, 'Gold'));
final cheap = contentType.entry().query()
..where('price_in_usd', QueryOperation(QueryOperationType.IsLessThan, 600));
final query = contentType.entry().query()
..operator(QueryOperator(QueryOperatorType.Or, [gold, cheap]));
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 entry in response['entries']) {
print(entry['title']);
}
}
} catch (e) {
// Thrown for a non-JSON response, a network failure or a 30-second timeout
print('Request did not complete: $e');
}
}All conditions: match entries that are Gold and cost less than 600
import 'package:contentstack/contentstack.dart' as contentstack;
import 'package:contentstack/src/enums/operations.dart';
import 'package:contentstack/src/enums/operations_type.dart';
import 'package:contentstack/src/enums/operator.dart';
import 'package:contentstack/src/enums/operator_type.dart';
Future<void> main() async {
final stack = contentstack.Stack('<API_KEY>', '<DELIVERY_TOKEN>', '<ENVIRONMENT>');
final contentType = stack.contentType('<CONTENT_TYPE_UID>');
final gold = contentType.entry().query()
..where('color', QueryOperation(QueryOperationType.Equals, 'Gold'));
final cheap = contentType.entry().query()
..where('price_in_usd', QueryOperation(QueryOperationType.IsLessThan, 600));
final query = contentType.entry().query()
..operator(QueryOperator(QueryOperatorType.And, [gold, cheap]));
final response = await query.find();
print(response['entries']);
}orderByAscending
orderByAscending sorts the entries that the find method returns by one field, from the lowest value to the highest.
| Name | Type | Description |
|---|---|---|
| key (required) | String | UID of the field to sort by. |
Returns: void. Nothing. The query keeps the setting for its next request.
Validation
- There is no client-side validation. An empty string reaches the request as asc=.
- An invalid value surfaces when find() 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. orderByAscending writes the asc URL parameter and makes no request. The find method sends it. See the Order by asc request.
- A second call replaces the first field. The query sorts by one field only.
- The orderByDescending method writes a different key (desc), so calling both sends both keys. Call only one of the two on a query.
- To sort by a field inside a Modular Blocks field, pass the path with dots, for example additional_info.rating.stars. See the Order by asc Operator within Modular Blocks request.
Example
Basic usage: sort entries by price, lowest first
import 'package:contentstack/contentstack.dart' as contentstack;
Future<void> main() async {
final stack = contentstack.Stack('<API_KEY>', '<DELIVERY_TOKEN>', '<ENVIRONMENT>');
final query = stack.contentType('<CONTENT_TYPE_UID>').entry().query()
..orderByAscending('price_in_usd');
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 entry in response['entries']) {
print('${entry['title']}: ${entry['price_in_usd']}');
}
}
} catch (e) {
// Thrown for a non-JSON response, a network failure or a 30-second timeout
print('Request did not complete: $e');
}
}orderByDescending
orderByDescending sorts the entries that the find method returns by one field, from the highest value to the lowest.
| Name | Type | Description |
|---|---|---|
| key (required) | String | UID of the field to sort by. |
Returns: void. Nothing. The query keeps the setting for its next request.
Validation
- There is no client-side validation. An empty string reaches the request as desc=.
- An invalid value surfaces when find() 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. orderByDescending writes the desc URL parameter and makes no request. The find method sends it. See the Order by desc request.
- A second call replaces the first field. The query sorts by one field only.
- The orderByAscending method writes a different key (asc), so calling both sends both keys. Call only one of the two on a query.
Example
Basic usage: list the most recently updated entries first
import 'package:contentstack/contentstack.dart' as contentstack;
Future<void> main() async {
final stack = contentstack.Stack('<API_KEY>', '<DELIVERY_TOKEN>', '<ENVIRONMENT>');
final query = stack.contentType('<CONTENT_TYPE_UID>').entry().query()
..orderByDescending('updated_at')
..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 entry in response['entries']) {
print('${entry['title']}: ${entry['updated_at']}');
}
}
} catch (e) {
// Thrown for a non-JSON response, a network failure or a 30-second timeout
print('Request did not complete: $e');
}
}param
param adds one URL parameter to the request that the find method sends.
| Name | Type | Description |
|---|---|---|
| key (required) | String | Name of the URL parameter. |
| value (required) | String | Value of the URL parameter. |
Returns: void. Nothing. The query keeps the setting for its next request.
Validation
- param ignores the call when key or value is an empty string. It throws nothing, so the parameter is missing from the request with no sign in your code.
- The SDK does not check the parameter name against the API. An unknown name or an invalid value surfaces when find() 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. param writes one key to the URL parameters of the query and makes no request.
- Use param for an API parameter that has no method of its own, for example include_count (see the Count request) or include_metadata (see the Get all entries request).
- A second call with the same key replaces the value. That includes keys that other methods write, such as limit, locale and environment.
- The addParam method does the same thing on a query. The addParams method writes several keys in one call.
- If the query contains a where condition or a related one, the find method writes the conditions under query and replaces your value. Do not pass query as the key.
Example
Basic usage: ask for the total number of matching entries
import 'package:contentstack/contentstack.dart' as contentstack;
Future<void> main() async {
final stack = contentstack.Stack('<API_KEY>', '<DELIVERY_TOKEN>', '<ENVIRONMENT>');
final query = stack.contentType('<CONTENT_TYPE_UID>').entry().query()
..param('include_count', 'true');
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 {
print('Total entries: ${response['count']}');
}
} catch (e) {
// Thrown for a non-JSON response, a network failure or a 30-second timeout
print('Request did not complete: $e');
}
}query
query adds a condition that matches entries whose field equals a string.
| Name | Type | Description |
|---|---|---|
| key (required) | String | UID of the field to test. |
| value (required) | String | String the field must equal. |
Returns: void. Nothing. The query keeps the setting for its next request.
Validation
- query ignores the call when key or value is an empty string. It throws nothing, so the condition is missing from the request with no sign in your code.
- Unlike the where method, query does not check the characters of the field UID.
- An invalid condition surfaces when find() 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. query adds "<key>": "<value>" to the condition object of the query and makes no request. The find method encodes that object as JSON and sends it as the query URL parameter. See the Equals Operator request.
- query sends the value as a string. To match a number or a boolean, use the where method with QueryOperationType.Equals.
- query, where, addQuery and whereReference write to the same condition object. A second condition on the same field replaces the first, whichever method wrote it.
Example
Basic usage: match entries by title
import 'package:contentstack/contentstack.dart' as contentstack;
Future<void> main() async {
final stack = contentstack.Stack('<API_KEY>', '<DELIVERY_TOKEN>', '<ENVIRONMENT>');
final query = stack.contentType('<CONTENT_TYPE_UID>').entry().query()
..query('title', 'Redmi 3S');
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 entry in response['entries']) {
print(entry['uid']);
}
}
} catch (e) {
// Thrown for a non-JSON response, a network failure or a 30-second timeout
print('Request did not complete: $e');
}
}removeHeader
removeHeader deletes a header from the requests of the stack that created the query.
| Name | Type | Description |
|---|---|---|
| key (required) | String | Name of the header to delete. |
Returns: void. Nothing. The stack uses the change on its next request.
Validation
- There is no client-side validation. removeHeader ignores a name that the stack does not hold and throws nothing.
- Deleting a header that the API needs, such as api_key or access_token, makes every later request from the stack fail. The API rejection comes back as the result of each call, with an error_code key.
Behavior
- Client-side only. removeHeader makes no request.
- removeHeader deletes from the header map of the stack, not of the query. Every later request from that stack goes out without the header, from this query, other queries, entries and assets alike. The removeHeader method of the Stack class changes the same map.
- The SDK writes Content-Type and X-User-Agent before each request, so deleting either header has no effect.
- Deleting the environment header leaves the environment URL parameter, which the query copied when you created it.
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>');
final query = stack.contentType('<CONTENT_TYPE_UID>').entry().query()
..setHeader('branch', '<BRANCH>');
// Later requests from this stack read the default branch again
query.removeHeader('branch');
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 {
print(response['entries']);
}
} 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 the requests of the stack that created the query, or replaces a header of the same name.
| Name | Type | Description |
|---|---|---|
| key (required) | String | Name of the header. |
| value (required) | String | Value of the header. |
Returns: void. Nothing. The stack uses the change on its next request.
Validation
- setHeader ignores the call when key or value is an empty string. It throws nothing.
- There is no check on the header name or value. A value that the API does not accept, such as a wrong access_token, fails on the next request. The API rejection comes back as the result of that call, with an error_code key.
Behavior
- Client-side only. setHeader makes no request.
- setHeader writes to the header map of the stack, not of the query. Every later request from that stack carries the header, from this query, other queries, entries and assets alike. The setHeader method of the Stack class changes the same map.
- A header of the same name takes the new value. That includes api_key, access_token, environment and branch.
- The SDK writes Content-Type and X-User-Agent before each request, so a value that you set for either header has no effect.
- The query copies the environment into its URL parameters when you create it. A new environment header does not change that parameter. Create a Stack for each environment instead.
Example
Basic usage: read the entries of one branch
import 'package:contentstack/contentstack.dart' as contentstack;
Future<void> main() async {
final stack = contentstack.Stack('<API_KEY>', '<DELIVERY_TOKEN>', '<ENVIRONMENT>');
final query = stack.contentType('<CONTENT_TYPE_UID>').entry().query()
..setHeader('branch', '<BRANCH>')
..includeBranch();
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 entry in response['entries']) {
print('${entry['title']}: ${entry['_branch']}');
}
}
} catch (e) {
// Thrown for a non-JSON response, a network failure or a 30-second timeout
print('Request did not complete: $e');
}
}skip
skip sets the number of entries that the API passes over before the page that the find method returns.
| Name | Type | Description |
|---|---|---|
| skipCount (required) | int | Number of matching entries to leave out. |
Returns: void. Nothing. The query keeps the setting for its next request.
Validation
- There is no client-side validation. skip converts the number to a string, so a negative number reaches the request unchanged.
- An invalid value surfaces when find() 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. skip writes the skip URL parameter and makes no request. The find method sends it. See the Skip request.
- Without skip, the page starts at the first matching entry.
- A second call replaces the first value.
- Each find call returns one page. The SDK does not request later pages. Combine skip with the limit method and an include_count parameter to read every entry, as the second example below shows. See the Pagination request.
Example
Basic usage: leave out the first ten entries
import 'package:contentstack/contentstack.dart' as contentstack;
Future<void> main() async {
final stack = contentstack.Stack('<API_KEY>', '<DELIVERY_TOKEN>', '<ENVIRONMENT>');
final query = stack.contentType('<CONTENT_TYPE_UID>').entry().query()..skip(10);
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 entry in response['entries']) {
print(entry['title']);
}
}
} catch (e) {
// Thrown for a non-JSON response, a network failure or a 30-second timeout
print('Request did not complete: $e');
}
}Pagination: read every entry, one page at a time
import 'package:contentstack/contentstack.dart' as contentstack;
Future<void> main() async {
final stack = contentstack.Stack('<API_KEY>', '<DELIVERY_TOKEN>', '<ENVIRONMENT>');
const pageSize = 100;
var skipped = 0;
final titles = <String>[];
while (true) {
final query = stack.contentType('<CONTENT_TYPE_UID>').entry().query()
..param('include_count', 'true')
..limit(pageSize)
..skip(skipped);
final response = await query.find();
for (final entry in response['entries'] as List) {
titles.add(entry['title'] as String);
}
skipped += pageSize;
if (skipped >= (response['count'] as int)) {
break;
}
}
print(titles.length);
}where
where adds a condition that matches entries by the value of one field.
| Name | Type | Description |
|---|---|---|
| fieldUid (required) | String | UID of the field to test. |
| queryOperation (required) | QueryOperation | Operator and value to apply to the field. |
Returns: void. Nothing. The query keeps the setting for its next request.
Validation
- where accepts a fieldUid made of letters, digits, -, _ and . only. For any other UID, including an empty string, where records nothing and throws nothing, so the condition is missing from the request with no sign in your code.
- There is no check on the value inside queryOperation. A value that JSON cannot encode, such as a DateTime, makes the find method throw JsonUnsupportedObjectError. Pass a date as an ISO 8601 string instead.
- An invalid condition surfaces when find() 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.
Example
Behavior
- Client-side only. where adds one key to the condition object of the query and makes no request. The find method encodes that object as JSON and sends it as the query URL parameter.
- Import QueryOperation and QueryOperationType from src/, because the package library does not export them. Add the following two import lines:
import 'package:contentstack/src/enums/operations.dart'; import 'package:contentstack/src/enums/operations_type.dart';
- Build the operation with two positional arguments, the type and the value: QueryOperation(QueryOperationType.IsLessThan, 600). The table below lists each type, the operator where writes, and the value to pass:
| QueryOperationType | Operator sent | Value to pass | API reference |
|---|---|---|---|
| Equals | None, the value itself | A value | Equals Operator |
| NotEquals | $ne | A value | Not-equals Operator |
| Includes | $in | A List of values | Array Equals Operator |
| Excludes | $nin | A List of values | Array Not-equals Operator |
| IsLessThan | $lt | A value | Less Than |
| IsLessThanOrEqual | $lte | A value | Less Than or Equal To |
| IsGreaterThan | $gt | A value | Greater Than |
| IsGreaterThanOrEqual | $gte | A value | Greater Than or Equal To |
| Exists | $exists | true or false | Exists |
| Matches | $regex | A regular expression as a String | Search by Regex |
- A call on a new field adds a key to the condition object. A second call on the same field replaces the first condition on that field. To put two operators on one field, pass both through the addQuery method, for example {'price_in_usd': {'\$gte': 100, '\$lte': 500}}.
- To test a field inside a Group field, pass the path with a dot, for example bank_offers.card_type.
- To match entries by a field of a referenced entry, use the whereReference method. To join conditions with $and or $or, use the operator method.
Basic usage: match entries by title
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>');
final query = stack.contentType('<CONTENT_TYPE_UID>').entry().query()
..where('title', QueryOperation(QueryOperationType.Equals, 'Redmi 3S'));
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 entry in response['entries']) {
print(entry['title']);
}
}
} catch (e) {
// Thrown for a non-JSON response, a network failure or a 30-second timeout
print('Request did not complete: $e');
}
}Several conditions: a list operator and a comparison on different fields
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>');
final query = stack.contentType('<CONTENT_TYPE_UID>').entry().query()
..where('color', QueryOperation(QueryOperationType.Includes, ['Gold', 'Black']))
..where('price_in_usd', QueryOperation(QueryOperationType.IsLessThan, 600));
final response = await query.find();
print(response['entries']);
}Pattern and presence: match a regular expression on entries that have a field
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>');
final query = stack.contentType('<CONTENT_TYPE_UID>').entry().query()
..where('title', QueryOperation(QueryOperationType.Matches, '^Blog'))
..where('url', QueryOperation(QueryOperationType.Exists, true));
final response = await query.find();
print(response['entries']);
}whereReference
whereReference adds a condition that matches entries by the fields of the entries that a reference field points to.
| Name | Type | Description |
|---|---|---|
| referenceUid (required) | String | UID of the reference field to test. |
| reference (required) | QueryReference | Match type and the query that holds the conditions. |
Returns: void. Nothing. The query keeps the setting for its next request.
Validation
- whereReference ignores the call when referenceUid is an empty string. It throws nothing, so the condition is missing from the request with no sign in your code.
- Unlike the where method, whereReference does not check the characters of the field UID.
- An invalid condition surfaces when find() 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.
Example
Behavior
- Client-side only. whereReference adds one key to the condition object of the query and makes no request. The find method sends it in the query URL parameter.
- Import QueryReference and QueryReferenceType from src/, because the package library does not export them. Add the following two import lines:
import 'package:contentstack/src/enums/reference.dart'; import 'package:contentstack/src/enums/reference_type.dart';
- Build the reference with two positional arguments, the type and a query: QueryReference(QueryReferenceType.Include, referencedQuery). The table below lists the two types:
| QueryReferenceType | Operator sent | Matches entries whose referenced entry | API reference |
|---|---|---|---|
| Include | $in_query | meets the conditions | Reference Search Equals |
| NotInclude | $nin_query | does not meet the conditions | Reference Search Not-equals |
- whereReference reads only the conditions of the inner query, the ones that where and related methods wrote. It ignores the content type of the inner query and its URL parameters. Write the conditions with the field UIDs of the referenced content type.
- A reference field can point to more than one content type. In that case, add a _content_type_uid condition to the inner query, as the second example below shows.
- The query keeps a reference to the inner query, not a copy. A condition that you add to the inner query later still reaches the next find call.
- A second call on the same reference field replaces the first condition, as does a where call on that field.
Basic usage: match products whose brand title is Apple Inc.
import 'package:contentstack/contentstack.dart' as contentstack;
import 'package:contentstack/src/enums/operations.dart';
import 'package:contentstack/src/enums/operations_type.dart';
import 'package:contentstack/src/enums/reference.dart';
import 'package:contentstack/src/enums/reference_type.dart';
Future<void> main() async {
final stack = contentstack.Stack('<API_KEY>', '<DELIVERY_TOKEN>', '<ENVIRONMENT>');
final contentType = stack.contentType('<CONTENT_TYPE_UID>');
// Only the conditions of this inner query reach the request
final brandQuery = contentType.entry().query()
..where('title', QueryOperation(QueryOperationType.Equals, 'Apple Inc.'));
final query = contentType.entry().query()
..whereReference('brand', QueryReference(QueryReferenceType.Include, brandQuery));
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 entry in response['entries']) {
print(entry['title']);
}
}
} catch (e) {
// Thrown for a non-JSON response, a network failure or a 30-second timeout
print('Request did not complete: $e');
}
}Exclusion across content types: leave out products of one brand
import 'package:contentstack/contentstack.dart' as contentstack;
import 'package:contentstack/src/enums/reference.dart';
import 'package:contentstack/src/enums/reference_type.dart';
Future<void> main() async {
final stack = contentstack.Stack('<API_KEY>', '<DELIVERY_TOKEN>', '<ENVIRONMENT>');
final contentType = stack.contentType('<CONTENT_TYPE_UID>');
final brandQuery = contentType.entry().query()
..query('title', 'Apple Inc.')
..query('_content_type_uid', 'brand');
final query = contentType.entry().query()
..whereReference('brand', QueryReference(QueryReferenceType.NotInclude, brandQuery));
final response = await query.find();
print(response['entries']);
}