Most SDK families make you learn the client three times: once for the server, once for mobile, once for the web build. The nRouter Dart guide takes the other bet. One pub package, nrouter, serves Flutter on mobile, web and desktop plus plain Dart VM programs, and the API surface is the same async Dart everywhere.
Full guide: https://nrouter.ai/docs/sdks/dart
Setup
dart pub add nrouter
# Flutter applications:
flutter pub add nrouter
The key comes from the environment — on mobile you pass it directly, and in Dart VM or CLI code String.fromEnvironment('NROUTER_API_KEY') picks it up at compile time. The client itself is one constructor:
import 'package:nrouter/nrouter.dart';
final client = NRouter(
apiKey: apiKey,
baseUrl: 'https://api.nrouter.ai/v1',
);
A call, and what comes back
final result = await client.chatCompletions({
'model': 'nrouter/auto',
'messages': [{'role': 'user', 'content': 'Hello!'}],
'nrouter_optimize': 'balanced',
});
print(result.body['choices'][0]['message']['content']);
if (result.meta.isPriced) {
print('Cost: ${result.meta.cost} | ID: ${result.meta.requestId}');
}
Two things worth noticing. The routing preference rides in the payload as ordinary map entries: 'nrouter/auto' plus 'nrouter_optimize' (quality, balanced or cost), with 'nrouter_cost_band' (low, mid, high) available under cost. And the response carries .meta extracted from the gateway's response headers, so cost and request ID arrive as typed fields. meta.isPriced is a small, honest touch: it tells you whether the cost figure is real before you print it.
Streaming is just await for
Streaming is Server-Sent Events, exposed as a Dart Stream:
final stream = client.messagesStream({
'model': 'nrouter/auto',
'messages': [{'role': 'user', 'content': 'Write a haiku.'}],
});
await for (final chunk in stream) {
print(chunk.delta);
}
No callback registration, no platform channels, nothing Flutter-specific. The same loop runs in a Flutter widget's state, a web build, or a command-line tool, because it is the language's own stream idiom all the way down.
Errors are a sealed family
Gateway refusals map to subclasses of NRouterError: NRouterRequestError (400, including cost_band_unsatisfiable), NRouterGuardrailBlockedError (400), NRouterAuthenticationError (401), NRouterCreditError (402), NRouterRateLimitError (429) and NRouterServiceError (503). Because the family is sealed, a Dart switch over the error type is exhaustive — the compiler makes you decide what each refusal means in your UI. And isRetryable is true for NRouterRateLimitError, NRouterServiceError and NRouterTransportError, so a retry policy is one check rather than a hand-maintained status table.
That is the whole shape: one cross-platform package that treats Dart's own idioms — futures, streams, sealed types — as the SDK design, and lets the gateway carry routing, budgets and guardrails behind one key. The guide has the full walkthrough: https://nrouter.ai/docs/sdks/dart
Top comments (0)