Skip to content

Cookie preferences

We use cookies for our own analytics, to see how our campaigns perform and, if you allow it, to load content from other services such as the Google site search. We never sell your data. Necessary cookies keep the site working and cannot be switched off. See our Cookie Policy for details and our Privacy Policy for how we handle personal data.

Security, load balancing and remembering your cookie choice.

Show us which pages people read, how they find the site and where they get stuck, so we can improve it (Google Analytics, Microsoft Clarity).

Show us which of our ad campaigns bring visitors to the site and remember the campaign or partner link you arrived from (Google Ads, LinkedIn, Meta, partner program). We do not use these cookies to build advertising profiles.

Load the site search from Google when you use it. Google sets its own cookies and shows ads in the search results.

© 2026 The ThingsBoard Authors

Dart API Client

The Dart ThingsBoard API Client lets Dart and Flutter applications manage ThingsBoard entities, work with telemetry, and receive real-time updates over WebSocket. It is generated from the ThingsBoard OpenAPI specification, so every REST endpoint and model of the platform is available as a typed API class. A hand-written runtime facade on top of the generated code handles JWT authentication with automatic token refresh, API key authentication, WebSocket telemetry subscriptions with auto-reconnect, and typed error handling.

The client is published as a single package, thingsboard_client, for ThingsBoard and ThingsBoard Cloud. The latest version is 5.0.0; it works with ThingsBoard 4.4.0 or later. The source code is in the dart_thingsboard_client repository, licensed under BSD 3-Clause.

Add the package to your project:

Terminal window
dart pub add thingsboard_client
# or for Flutter projects
flutter pub add thingsboard_client

This adds to pubspec.yaml:

dependencies:
thingsboard_client: ^5.0.0

The client requires Dart 3.10 (Flutter 3.38) or later and ThingsBoard 4.4.0 or later. It runs on Flutter mobile (iOS, Android), Flutter Web, and plain Dart.

Import the package in Dart code. The main library exports the generated API classes and models together with the runtime facade:

import 'package:thingsboard_client/thingsboard_client.dart';

Create a client instance, log in, inspect the authenticated user, and log out:

import 'package:thingsboard_client/thingsboard_client.dart';
const thingsBoardApiEndpoint = 'http://localhost:8080';
void main() async {
final tbClient = ThingsboardClient(thingsBoardApiEndpoint);
try {
await tbClient.login(LoginRequest((b) => b
..username = '[email protected]'
..password = 'tenant'));
print('isAuthenticated=${tbClient.isAuthenticated()}');
final authUser = tbClient.getAuthUser();
print('authUser: ${authUser?.userId} (${authUser?.authority})');
await tbClient.logout();
} catch (e) {
final error = toThingsboardError(e);
print('ThingsBoard error: ${error.message} (${error.errorCode})');
}
}

ThingsboardClient accepts optional named parameters:

  • storage — a TbStorage implementation that persists the JWT and refresh tokens between runs. InMemoryStorage is the default; LocalFileStorage is also bundled. Call tbClient.init() at startup to restore a stored session and refresh the token if it has expired.
  • apiKey — authenticate with an API key instead of a user session (see below).
  • onUserLoaded, onMfaAuth, onMfaForce, onError, onLoadStarted, onLoadFinished — callbacks for the authentication lifecycle, two-factor authentication prompts, request errors, and request activity.
  • debugMode — logs every request and response to the console.

You can authenticate with an API key instead of a username and password. Pass the key to the constructor; every REST request and the WebSocket are then authenticated with it. No login() call is needed:

import 'package:thingsboard_client/thingsboard_client.dart';
const thingsBoardApiEndpoint = 'http://localhost:8080';
const apiKey = 'tb_your_api_key';
void main() async {
final tbClient = ThingsboardClient(thingsBoardApiEndpoint, apiKey: apiKey);
try {
final device = Device((b) => b
..name = 'myDevice'
..type = 'default');
final savedDevice = await tbClient.getDeviceControllerApi().saveDevice(device: device);
print('savedDevice: ${savedDevice.data?.name} (${savedDevice.data?.id?.id})');
} catch (e) {
final error = toThingsboardError(e);
print('ThingsBoard error: ${error.message} (${error.errorCode})');
}
}

Generated API classes are grouped by REST controller and obtained from the client with getXxxControllerApi() methods. List endpoints take pageSize and page arguments and return the page wrapped in a Dio Response; the payload is in response.data. Paginate through all devices belonging to the current tenant:

import 'package:thingsboard_client/thingsboard_client.dart';
const thingsBoardApiEndpoint = 'http://localhost:8080';
void main() async {
final tbClient = ThingsboardClient(thingsBoardApiEndpoint);
try {
await tbClient.login(LoginRequest((b) => b
..username = '[email protected]'
..password = 'tenant'));
final deviceApi = tbClient.getDeviceControllerApi();
var page = 0;
PageDataDevice? devices;
do {
final response = await deviceApi.getTenantDevices(pageSize: 10, page: page);
devices = response.data;
for (final device in devices?.data ?? <Device>[]) {
print('${device.name} (${device.type})');
}
import 'package:thingsboard_client/thingsboard_client.dart';
const thingsBoardApiEndpoint = 'http://localhost:8080';
void main() async {
final tbClient = ThingsboardClient(thingsBoardApiEndpoint);
try {
await tbClient.login(LoginRequest((b) => b
..username = '[email protected]'
..password = 'tenant'));
final dashboardApi = tbClient.getDashboardControllerApi();
var page = 0;
PageDataDashboardInfo? dashboards;
do {
final response = await dashboardApi.getTenantDashboards(pageSize: 10, page: page);
dashboards = response.data;
for (final dashboard in dashboards?.data ?? <DashboardInfo>[]) {
print('${dashboard.title} (${dashboard.id?.id})');
}

Models are immutable built_value classes created through a builder. Polymorphic models such as entity filters and key filter predicates set their type discriminator themselves, so you don’t pass it. Use the Entity Data Query API to count all devices and then only the active ones:

import 'package:thingsboard_client/thingsboard_client.dart';
const thingsBoardApiEndpoint = 'http://localhost:8080';
void main() async {
final tbClient = ThingsboardClient(thingsBoardApiEndpoint);
try {
await tbClient.login(LoginRequest((b) => b
..username = '[email protected]'
..password = 'tenant'));
final entityQueryApi = tbClient.getEntityQueryControllerApi();
// Entity filter that selects all devices
final allDevicesQuery = EntityCountQuery((b) => b
..entityFilter = EntityTypeFilter((f) => f..entityType = EntityType.DEVICE));
final totalDevices = await entityQueryApi.countEntitiesByQuery(entityCountQuery: allDevicesQuery);
print('Total devices: ${totalDevices.data}');
// Same filter plus a key filter on the "active" attribute
final activeDevicesQuery = allDevicesQuery.rebuild((b) => b
..keyFilters.add(KeyFilter((k) => k
..key.type = EntityKeyType.ATTRIBUTE
..key.key = 'active'
..valueType = EntityKeyValueType.BOOLEAN
..predicate = BooleanFilterPredicate((p) => p
..operation = BooleanOperation.EQUAL
..value.defaultValue = true))));
final activeDevices = await entityQueryApi.countEntitiesByQuery(entityCountQuery: activeDevicesQuery);
print('Active devices: ${activeDevices.data}');
await tbClient.logout();
} catch (e) {
final error = toThingsboardError(e);
print('ThingsBoard error: ${error.message} (${error.errorCode})');
}
}

Create a device, save and read shared attributes through the Telemetry controller, then delete the device. Attribute and telemetry payloads are passed as JSON strings, exactly as the REST API expects them:

import 'dart:convert';
import 'package:thingsboard_client/thingsboard_client.dart';
const thingsBoardApiEndpoint = 'http://localhost:8080';
void main() async {
final tbClient = ThingsboardClient(thingsBoardApiEndpoint);
try {
await tbClient.login(LoginRequest((b) => b
..username = '[email protected]'
..password = 'tenant'));
final deviceApi = tbClient.getDeviceControllerApi();
final telemetryApi = tbClient.getTelemetryControllerApi();
final device = Device((b) => b
..name = 'My test device'
..type = 'default'
..label = 'Created from Dart');
final savedDevice = (await deviceApi.saveDevice(device: device)).data!;
final deviceId = savedDevice.id!.id;
print('savedDevice: ${savedDevice.name} ($deviceId)');
final foundDevice = (await deviceApi.getDeviceInfoById(deviceId: deviceId)).data;
print('foundDevice: ${foundDevice?.name}');
// Save shared attributes
await telemetryApi.saveEntityAttributesV2(
entityType: 'DEVICE',
entityId: deviceId,
scope: 'SHARED_SCOPE',
body: jsonEncode({'targetTemperature': 22.4, 'targetHumidity': 57.8}),
);
// Read shared attributes back
final attributes = await telemetryApi.getAttributesByScope(
entityType: 'DEVICE',
entityId: deviceId,
scope: 'SHARED_SCOPE',
keys: 'targetTemperature,targetHumidity',

tbClient.getTelemetryService() returns the WebSocket telemetry service. Wrap one or more subscription commands in a TelemetrySubscriber, listen to its stream, and call subscribe(). The subscriber reconnects automatically if the connection drops. Subscriptions use the generated models, including entity ids such as DeviceId((b) => b..id = uuid).

The example subscribes to the latest temperature and humidity telemetry of a device, then posts sample values through the REST API so the updates arrive over WebSocket:

import 'dart:convert';
import 'dart:math';
import 'package:thingsboard_client/thingsboard_client.dart';
const thingsBoardApiEndpoint = 'http://localhost:8080';
void main() async {
final tbClient = ThingsboardClient(thingsBoardApiEndpoint);
try {
await tbClient.login(LoginRequest((b) => b
..username = '[email protected]'
..password = 'tenant'));
final deviceApi = tbClient.getDeviceControllerApi();
final telemetryApi = tbClient.getTelemetryControllerApi();
final device = Device((b) => b
..name = 'My test device'
..type = 'default');
final savedDevice = (await deviceApi.saveDevice(device: device)).data!;
final deviceId = savedDevice.id!.id;
// Subscribe to the latest telemetry of the device
final subscriber = TelemetrySubscriber.createEntityAttributesSubscription(
telemetryService: tbClient.getTelemetryService(),
entityId: savedDevice.id!,
attributeScope: LatestTelemetry.LATEST_TELEMETRY.toShortString(),
keys: ['temperature', 'humidity'],
);
subscriber.attributeDataStream.listen((attributes) {
for (final attribute in attributes) {
print('${attribute.key} = ${attribute.value} at ${attribute.lastUpdateTs}');
}
});
subscriber.subscribe();
// Post sample telemetry
final rng = Random();
for (var i = 0; i < 5; i++) {
await Future.delayed(const Duration(seconds: 1));

Other subscription types follow the same pattern. Pass the matching command to TelemetrySubscriber and listen to the corresponding stream:

  • createEntityAttributesSubscription() — attributeDataStream with the current values, as above; dataStream with the raw updates
  • EntityDataCmd — entityDataStream, entity data query results with live telemetry updates
  • AlarmDataCmd — alarmDataStream
  • EntityCountCmd — entityCountStream
  • createNotificationsSubscription() and createNotificationCountSubscription() — notificationStream and notificationCountStream
  • reconnectStream fires after the WebSocket connection has been re-established

Failed requests surface as a ThingsboardError with a message, an errorCode from the ThingsBoardErrorCode enum (for example authentication, jwtTokenExpired, permissionDenied, itemNotFound, tooManyRequests), and the HTTP status when available. Facade methods such as login() throw it directly; generated API classes throw a Dio DioException that carries the ThingsboardError in its error field. toThingsboardError() normalizes either form, so a single catch block covers both:

try {
await tbClient.getDeviceControllerApi().getDeviceById(deviceId: 'missing-id');
} catch (e) {
final error = toThingsboardError(e);
switch (error.errorCode) {
case ThingsBoardErrorCode.itemNotFound:
print('No such device');
case ThingsBoardErrorCode.permissionDenied:
print('Not allowed: ${error.message}');
default:
print('Request failed (${error.status}): ${error.message}');
}
}

The onError constructor callback receives the same ThingsboardError for every failed request, which is convenient for global handling such as redirecting to the login screen when the session expires.

thingsboard_client 5.0.0 replaces two earlier packages. The migration guide in the repository lists every change; the main ones are below.

Rename the dependency and the imports. Apart from the changes listed below, the API classes and the ThingsboardClient facade are the same as in 4.4.x:

dependencies:
thingsboard_client: ^5.0.0 # was thingsboard_pe_client: ^4.4.0
Terminal window
grep -rl 'package:thingsboard_pe_client/' lib test | xargs sed -i -e 's#package:thingsboard_pe_client/thingsboard_pe_client\.dart#package:thingsboard_client/thingsboard_client.dart#g' -e 's#package:thingsboard_pe_client/#package:thingsboard_client/#g'

On macOS, use sed -i '' instead of sed -i. Then:

  • Import only the main library. Delete the hide clauses and src/... imports used with 4.4.x: LoginRequest, EntityId and EntityType now come from the main library, and a hide would hide them.
  • Log in with a builder: LoginRequest((b) => b..username = user..password = password).
  • Entity ids and WebSocket queries are built models: DeviceId((b) => b..id = uuid), EntityDataQuery((b) => ...). Most generated subtypes set their discriminators themselves.
  • Some enum constants are renamed after their value (for example oAUTH2CLIENT → OAUTH2_CLIENT), and FontWeight / FontStyle are renamed to TbFontWeight / TbFontStyle.
  • DeviceApiControllerApi is removed: devices should use the MQTT, CoAP or HTTP transport directly.

The hand-written client, last released as 4.2.1, is replaced by generated API classes:

Legacy client (4.2.1) thingsboard_client 5.0.0
Hand-written services: tbClient.getDeviceService() One generated class per REST controller: tbClient.getDeviceControllerApi()
getTenantDevices(PageLink(10)) getTenantDevices(pageSize: 10, page: 0)
Methods return the model directly Methods return a Dio Response<T>; the model is in response.data
Mutable models: Device('name', 'default') Immutable built_value models: Device((b) => b..name = 'name'..type = 'default')
LoginRequest('user', 'password') LoginRequest((b) => b..username = 'user'..password = 'password')
saveEntityAttributesV2(entityId, scope, {...}) saveEntityAttributesV2(entityType: 'DEVICE', entityId: id, scope: 'SHARED_SCOPE', body: jsonEncode({...}))
Requires ThingsBoard 3.6.3 or later Requires ThingsBoard 4.4.0 or later

The WebSocket layer (TelemetrySubscriber and its streams) works the same way, but uses the generated models.

Catch errors as shown in Error handling. Generated API calls throw DioException, not ThingsboardError, so an on ThingsboardError clause no longer catches them.

Getters such as getDevice returned null on HTTP 404; their replacements, such as getDeviceById, throw. To get null back, wrap the call: (await nullIfNotFound(() => tbClient.getDeviceControllerApi().getDeviceById(deviceId: id)))?.data. The 404 still reaches onError; pass extra: InterceptorConfig(ignoreErrors: true).toExtra() to keep it out.