---
slug: dart-add-servicestack-reference
title: Dart Add ServiceStack Reference
---

ServiceStack's **Add ServiceStack Reference** feature allows clients to generate Native Types from a simple [@servicestack/cli command-line utility](https://github.com/ServiceStack/servicestack-cli#servicestackcli) - providing a simple way to give clients typed access to your ServiceStack Services.
## Dart Android Example using Android Studio
### Dart ServiceStack Reference
Dart ServiceStack Reference supports **all Dart 2.0 platforms**, including Flutter and AngularDart or Dart Web Apps - in the same optimal development workflow pioneered in [Add ServiceStack Reference](/add-servicestack-reference) where it doesn't requiring any additional tooling, transformers or build steps.
Due to the lack of reflection and Mirror support, consuming JSON APIs can be quite [cumbersome in Flutter](https://flutter.io/cookbook/networking/fetch-data/). But we've been able to achieve the same productive development experience available in [all supported languages](/add-servicestack-reference) where you can use the generated Dart DTOs from any remote v5.1+ ServiceStack endpoint with ServiceStack's Smart generic
[JsonServiceClient](https://pub.dartlang.org/documentation/servicestack/0.0.7/client/JsonServiceClient-class.html) available in the [servicestack Dart package](https://pub.dartlang.org/packages/servicestack#-installing-tab-), to enable an end-to-end Typed API for calling Services by [sending and receiving native DTOs](/architecture-overview#client-architecture).
### Install
You can use the same [x dotnet tool](/dotnet-tool) simple command-line utility to easily Add and Update ServiceStack References for all supported languages:
Install [.NET SDK](https://dotnet.microsoft.com/download) then install the `x` dotnet tool:
:::sh
dotnet tool install --global x
:::
::include npx-get-dtos.md::
### Example Usage
You can then execute `x dart` with the URL of the remote ServiceStack Instance you want to generated DTOs for, e.g:
:::sh
`x dart https://techstacks.io`
:::
This will generate Dart DTOs for the [entire TechStacks API](https://techstacks.io/metadata):
```
Saved to: dtos.dart
```
::: info
If no name is specified in the 2nd argument, it uses `dtos` if it doesn't exist, otherwise falls back to infer it from the URL
:::
To make API calls we need to use the `JsonServiceClient`, installed by adding the [servicestack](https://pub.dartlang.org/packages/servicestack#-installing-tab-) package to our Dart projects `pubspec.yaml`:
```yaml
dependencies:
servicestack: ^2.0.1
```
Saving `pubspec.yaml` in VS Code with the [Dart Code Extension](https://dartcode.org) automatically calls `pub get` or `flutter packages get` (in Flutter projects) to add any new dependencies to your project.
We now have everything we need to be able to make typed API requests to any of [TechStacks APIs](https://techstacks.io/metadata) with a shared `JsonServiceClient` instance populated with the base URL of the remote endpoint, e.g:
```dart
import 'package:servicestack/client.dart';
import 'dtos.dart';
var client = JsonServiceClient("https://techstacks.io");
main() async {
var response = await client.get(GetTechnology(slug: "flutter"));
print("${response.technology.name}: ${response.technology.vendorUrl}");
}
```
Like C#, Dart has Generics and Type Inference so the `response` returned is the typed `HelloResponse` DTO giving us rich intelli-sense and compiler type safety.
### Platform neutral usage
Both **dart:io** `JsonServiceClient` and **dart:html** `JsonWebClient` implement the same shared `IServiceClient` interface which support a platform-neutral source-compatible API using the
`ClientFactory` APIs, e.g:
```dart
import 'package:servicestack/web_client.dart' if (dart.library.io) 'package:servicestack/client.dart';
main() async {
var client = ClientFactory.create('https://techstacks.io');
var response = await client.get(GetTechnology(slug: "flutter"));
print("${response.technology.name}: ${response.technology.vendorUrl}");
}
```
For advanced configuration you can use the `createWith(ClientOptions)` API, e.g you can use `dev.servicestack.com` which resolves to `10.0.2.2`
which in Android you can use to access `127.0.0.1` of the host OS allowing you to access your local development server.
In this example we'll create either a typed Service Client to our local development server in **Debug** during development (ignoring its self-signed certificate)
and our production server in **Release** mode:
```dart
import 'package:servicestack/web_client.dart' if (dart.library.io) 'package:servicestack/client.dart';
import 'package:flutter/foundation.dart';
main() async {
var client = kDebugMode
? ClientFactory.createWith(ClientOptions(baseUrl:'https://dev.servicestack.com:5001', ignoreCert:true))
: ClientFactory.create('https://techstacks.io');
}
```
::: info Tip
If you add a `127.0.0.1 dev.servicestack.com` mapping in your OS's `hosts` file you'll also be able to use `dev.servicestack.com` to access your local dev server in your Host OS
:::
### Shared Initialization Configuration
For more advanced configuration you can use the `ClientConfig.initClient` client factory filter to customize all service client instances
as done in this example to configure all client instances with any previously saved JWT Bearer & Refresh Tokens to enable authenticated access:
```dart
import 'package:flutter/foundation.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:servicestack/web_client.dart' if (dart.library.io) 'package:servicestack/client.dart';
SharedPreferences prefs;
IServiceClient client;
AuthenticateResponse auth;
Future main() async {
runApp(MyApp());
ClientConfig.initClient = (client) {
if (auth != null) {
client.bearerToken = auth.bearerToken;
client.refreshToken = auth.refreshToken;
}
};
prefs = await SharedPreferences.getInstance();
var json = prefs.getString('auth');
auth = json != null
? AuthenticateResponse.fromJson(jsonDecode(json))
: null;
client = ClientFactory.createWith(ClientOptions(
baseUrl:'https://dev.servicestack.com:5001', ignoreCert:kDebugMode));
}
```
#### AngularDart and Dart Web Usage
For AngularDart or Dart Web Apps import `web_client.dart` and use the `JsonWebClient`:
```dart
import 'package:servicestack/web_client.dart';
import 'dtos.dart'; // Add ServiceStack Reference DTOs
//...
var client = JsonWebClient("https://techstacks.io");
var response = await client.get(GetTechnology(slug: "flutter"));
```
See the [HelloAngularDart](https://github.com/ServiceStackApps/HelloAngularDart) project for a working example.
#### Platform agnostic Usage
For creating libraries that can be consumed in any Dart platform reference `servicestack.dart` and use the `IServiceClient` interface which
is implemented by both `JsonServiceClient` and `JsonWebClient`:
```dart
import 'package:servicestack/servicestack.dart';
import 'dtos.dart'; // Add ServiceStack Reference DTOs
//...
fetchTechnologies(IServiceClient client) async {
var response = await client.get(GetTechnology(slug: "flutter"));
}
```
### Rich Generated Models
Thanks to the direct C# to Dart model code generation we're able to create the ideal idiomatic message-based APIs utilizing rich typed models with broad support for many of the C#/.NET features used when defining DTOs inc. Generics, Inheritance, multiple Interfaces, Enums (inc. int and Flag Enums), Tuples, metadata Attributes emitted in comments (emitting additional documentation in the generated models) whilst also taking care of mapping built-in C# Types like `DateTime`, `TimeSpan`, `byte[]` and `Stream` into their equivalent native Dart [DateTime](https://api.dartlang.org/stable/1.24.3/dart-core/DateTime-class.html), [Duration](https://api.dartlang.org/stable/1.24.3/dart-core/Duration-class.html) and [Uint8List](https://api.dartlang.org/stable/1.24.3/dart-typed_data/Uint8List-class.html) types, C# generic collections are also converted into their equivalent Dart generic collection Type.
#### JsonCodec compatible
The generated DTOs follow Dart's [JsonCodec](https://api.dartlang.org/stable/1.24.3/dart-convert/JsonCodec-class.html) pattern allowing them to be individually serializable with Dart's universal JSON encode/decode APIs, e.g:
```dart
//Serialization
var dto = MyDto(name:"foo");
String jsonString = json.encode(dto);
//Deserialization
Map jsonObj = json.decode(jsonString);
var fromJson = MyDto.fromJson(jsonObj);
```
#### Default Constructor
All DTOs also include a default constructor containing all properties as optional arguments providing a wrist-friendly syntax for creating and populating DTOs in a single constructor expression, e.g:
```dart
var request = MyDto(name:"foo");
```
Only the properties of each DTO are included in its default constructor so you'll need to use property accessors to initialize any fields in base classes, but thanks to Dart's support for method cascades you can still populate an entire DTO with a single expression, e.g:
```dart
var request = FindTechnologies(name:"Flutter")
..fields = "id,slug,vendorName,productUrl"
..orderBy = "created,-viewCount"
..take = 1;
```
#### IConvertible
All DTOs implement the `IConvertible` interface below where each instance can be converted to and from a Map of values, giving each model dynamism that's otherwise not possible in Flutter:
```csharp
abstract class IConvertible
{
TypeContext context;
fromMap(Map map);
Map toJson();
}
```
The conversion logic that handles the behind-the-scenes conversion into and out of Dart Types is maintained in the extensible [JsonConverters](https://pub.dartlang.org/documentation/servicestack/0.0.7/client/JsonConverters/Converters.html) class which lets you replace built-in converters with your own implementation or register new Converters when you want to take over handling of specific types.
### JsonServiceClient
The `JsonServiceClient` is a smart full-featured Service Client implementation with a number of high-level features that make consuming ServiceStack APIs a seamless experience, with built-in support for:
- HTTP Basic Auth (inc. [API Key support](/auth/api-key-authprovider))
- [Cookies, Sessions and Credential Auth](/auth/sessions)
- [JWT, including using RefreshTokens to auto-fetch new JWT Bearer Tokens](/auth/jwt-authprovider)
- [Structured Error Handling](/error-handling)
- [Auto Batched Requests](/auto-batched-requests)
- Global and per-instance Request, Response and Exception Filters
- `onAuthenticationRequired` hook to handle re-authentication and transparent replay of failed 401 requests
Behind the scenes `JsonServiceClient` leverages the optimal [`HttpClient` in dart:io](https://docs.flutter.io/flutter/dart-io/HttpClient-class.html) to perform HTTP Requests in Flutter and Dart VM Apps.
### JsonWebClient
The `JsonWebClient` performs HTTP Requests using [dart:html BrowserClient](https://webdev.dartlang.org/angular/guide/server-communication) to use the browsers built-in `XMLHttpRequest` object. Despite their implementation differences `JsonWebClient` also supports the same feature-set as the Dart VM's `JsonServiceClient` above.
AngularDart or Dart Web Apps can use `JsonWebClient` by importing `web_client.dart`, e.g:
```dart
import 'package:servicestack/web_client.dart';
var client = JsonWebClient("https://techstacks.io");
```
### IServiceClient API
Both JSON Service Client variants implement the same flexible `IServiceClient` API below, use the same DTOs and implementation and throws the same structured `WebServiceException` which results in Typed API Requests being source-compatible between Dart Web Apps, Dart VM Server and AOT compiled Flutter Web Apps:
```csharp
abstract class IServiceClient {
String? baseUrl;
String? replyBaseUrl;
String? oneWayBaseUrl;
String? bearerToken;
String? refreshToken;
String? userName;
String? password;
AsyncCallbackFunction? onAuthenticationRequired;
String? getTokenCookie();
String? getRefreshTokenCookie();
void clearCookies();
Future> api(IReturn request, {Map? args, String? method});
Future> apiVoid(IReturnVoid request, {Map? args, String? method});
Future get(IReturn request, {Map? args});
Future