API reference
Every public Dart API in the Sophonz Flutter SDK — lifecycle, errors, logs, spans, network requests, views, users, sessions, exporters and the OpenTelemetry API — with signatures and Android and iOS support.
Most of the API is on Sophonz.instance. Each call is forwarded to the native SDK over a method channel, so most methods return immediately and the work happens natively. Methods that return void never throw: a failure, including a call made before start(), is dropped. A call is not queued until the SDK starts.
Imports
| Import | Provides |
|---|---|
package:sophonz/sophonz.dart | Sophonz, SophonzNavigationObserver, SophonzScreenLoadConfig, SophonzRouteSettingsExtractor, SophonzHttpClient, HttpMethod, W3cTraceContext |
package:sophonz/sophonz_api.dart | SophonzSpan, SophonzSpanEvent, SophonzNetworkRequest, Severity |
package:sophonz_platform_interface/sophonz_platform_interface.dart | ErrorCode |
package:sophonz_platform_interface/last_run_end_state.dart | LastRunEndState |
package:sophonz/sophonz_samples.dart | SophonzSamples, test triggers |
package:sophonz_dio/sophonz_dio.dart | SophonzInterceptor |
package:sophonz_go_router/sophonz_go_router.dart | SophonzGoRouterObserver |
sophonz.dart does not re-export the types in the other rows. Importing sophonz_platform_interface directly means listing it in pubspec.yaml, under both dependencies and dependency_overrides (see Installation).
NOTE — Severity exists twice
sophonz_api.dart and dartastic_opentelemetry_api both declare Severity. In a file that imports both, hide one: import 'package:dartastic_opentelemetry_api/dartastic_opentelemetry_api.dart' hide Severity;.
Platform support
| API | Android | iOS |
|---|---|---|
| Lifecycle, errors, logs, breadcrumbs | yes | yes |
Spans (startSpan, recordCompletedSpan, SophonzSpan) | yes | yes |
recordNetworkRequest | yes; standard methods only | yes |
startView, endView | yes | yes |
setUserIdentifier, personas, payer | yes | yes; personas last for the process |
setUserName, setUserEmail | yes | ignored |
Session properties, endSession | yes | yes; endSession at most once per 5 s |
logPushNotification | yes | yes; needs title and body |
addSpanExporter, addLogRecordExporter | yes; before start | ignored |
| OpenTelemetry API spans | partly, see below | partly |
Lifecycle
| Signature | Description |
|---|---|
Future<void> start({FutureOr<void> Function()? action}) | Attaches to the native SDK and starts Dart-side capture. With action, installs error handlers, runs action and records time to first frame |
Future<void> installErrorHandlers(FutureOr<void> Function() action) | Installs the error handlers and runs action, for when start was called without one |
void disable() | Stops capture in Dart and the native SDK. It cannot be restarted in the same process |
Future<LastRunEndState> getLastRunEndState() | crash, cleanExit, or invalid when unknown or the SDK is not running |
Future<String?> getDeviceId() | The device identifier the native SDK assigned, or null |
start also accepts enableIntegrationTesting, which is deprecated and has no effect.
import 'package:sophonz_platform_interface/last_run_end_state.dart';
final lastRun = await Sophonz.instance.getLastRunEndState();
if (lastRun == LastRunEndState.crash) {
showCrashRecoveryHint();
}Call start once. A second call does not attach again, but it installs the frame, hang and lifecycle monitors and the error handlers a second time.
Errors
Uncaught errors are captured once start(action: ...) or installErrorHandlers has run. Record caught errors yourself:
try {
await checkout();
} catch (error, stack) {
Sophonz.instance.logHandledDartError(error, stack);
}| Signature | Description |
|---|---|
void logDartError(Object error, StackTrace stack) | Records an error as unhandled |
void logHandledDartError(Object error, StackTrace stack) | Records an error as handled. It does not count against error-free sessions |
Errors are error-severity logs with exception.type, exception.message, exception.stacktrace and spz.exception_handling. The stack is the Dart stack. See Instrumentation.
Logs and breadcrumbs
Sophonz.instance.logInfo('Checkout started');
Sophonz.instance.logError('Payment declined', properties: {'order.id': 'A-1042'});
Sophonz.instance.addBreadcrumb('Tapped pay');| Signature | Description |
|---|---|
void logInfo(String message, {Map<String, String>? properties}) | Info-level log |
void logWarning(String message, {Map<String, String>? properties}) | Warning-level log |
void logError(String message, {Map<String, String>? properties}) | Error-level log |
void logMessage(String message, Severity severity, {Map<String, String>? properties}) | Log at Severity.info, warning or error |
void addBreadcrumb(String message) | A lightweight event on the session timeline |
properties become log attributes. Keep personal data out of them.
Push notifications
void logPushNotification(
String? title,
String? body, {
String? subtitle,
int? badge,
String? category,
String? from,
String? messageId,
int? priority,
bool hasNotification = false,
bool hasData = false,
})| Parameter | Platform |
|---|---|
title, body | both. On iOS nothing is recorded unless both are non-null |
subtitle, badge, category | iOS |
from, messageId, priority, hasNotification, hasData | Android |
On iOS, notifications delivered through UNUserNotificationCenter can be captured natively instead, by adding PushNotificationCaptureService at start (Configuration). Do not do both for the same notification.
Spans
import 'package:sophonz/sophonz.dart';
import 'package:sophonz_platform_interface/sophonz_platform_interface.dart' show ErrorCode;
final span = await Sophonz.instance.startSpan('load-catalog');
try {
final items = await loadCatalog();
await span?.addAttribute('item.count', '${items.length}');
await span?.stop();
} catch (_) {
await span?.stop(errorCode: ErrorCode.failure);
rethrow;
}| Signature | Description |
|---|---|
Future<SophonzSpan?> startSpan(String name, {SophonzSpan? parent, int? startTimeMs}) | Starts a span. null if the SDK is not running or the span could not be created |
Future<bool> recordCompletedSpan(String name, int startTimeMs, int endTimeMs, {ErrorCode? errorCode, SophonzSpan? parent, Map<String, String>? attributes, List<SophonzSpanEvent>? events}) | Records a span that already happened. Times are epoch milliseconds |
Future<T> recordSpan<T>(String name, {SophonzSpan? parent, Map<String, String>? attributes, List<SophonzSpanEvent>? events, required Future<T> Function() code}) | Runs code between a start and a stop |
A span without parent starts a new trace.
SophonzSpan
| Member | Description |
|---|---|
String id | Span ID |
Future<String?> traceId | Trace ID |
Future<bool> stop({ErrorCode? errorCode, int? endTimeMs}) | Ends the span. ErrorCode.failure, abandon or unknown mark it failed |
Future<bool> addEvent(String name, {int? timestampMs, Map<String, String>? attributes}) | Adds a span event, at the current time if timestampMs is omitted |
Future<bool> addAttribute(String key, String value) | Adds a string attribute |
The bool results are false when the span was not found, for example after it was stopped.
SophonzSpanEvent({required String name, required int timestampMs, required Map<String, String> attributes}) describes an event for recordCompletedSpan.
final start = DateTime.now().millisecondsSinceEpoch;
final image = await decodeImage(bytes);
await Sophonz.instance.recordCompletedSpan(
'decode-image',
start,
DateTime.now().millisecondsSinceEpoch,
attributes: {'image.bytes': '${bytes.length}'},
);CAUTION — recordSpan swallows failures and ignores attributes
If the SDK is not running, recordSpan does not run code at all. If code throws, the exception is not rethrown, the span is left open, and recordSpan returns a default value (null, false, 0, 0.0 or an empty string). attributes and events are accepted but not applied. For work that can fail, use startSpan and stop(errorCode:) as above.
NOTE — Spans count against the native span limit
Spans from Dart are custom spans to the native SDK. They share its per-session limit with every other custom span, including screen-load spans and, on iOS, network spans recorded from Dart. Keep names low-cardinality and put IDs in attributes.
A span that is started and never stopped stays in the native plugin's memory for the life of the process.
OpenTelemetry API
The SDK registers itself as the tracer and logger provider of dartastic_opentelemetry_api (1.0.0-rc.3), so code written against the OpenTelemetry Dart API records into Sophonz. Add the package to pubspec.yaml at that version to import it.
import 'package:dartastic_opentelemetry_api/dartastic_opentelemetry_api.dart' hide Severity;
final tracer = OTelAPI.tracerProvider().getTracer('checkout');
final span = tracer.startSpan('validate-cart');
span.setIntAttribute('cart.size', cart.items.length);
try {
await tracer.withSpanAsync(span, validateCart);
} catch (error, stack) {
span.recordException(error, stackTrace: stack);
rethrow;
} finally {
span.end();
}Every tracer name returns the same tracer. What the bridge supports in 0.1.0:
| OpenTelemetry call | Result |
|---|---|
startSpan, createSpan, end | Native span started and stopped. createSpan(startTime:) and end(endTime:) are honoured |
setStringAttribute, setIntAttribute, other setters, addAttributes | Sent as string attributes. Lists are joined with commas |
addEvent, addEventNow, addEvents | Span events |
recordException | An exception event with exception.type, exception.message, exception.stacktrace |
withSpan, withSpanAsync | Make the span current, which SophonzHttpClient and SophonzInterceptor use for traceparent |
setStatus, end(spanStatus:), updateName, addLink | Not implemented by the native plugins. The call fails asynchronously and can surface as an unhandled Dart error log |
Parent spans (parentSpan:, or a current span) | Not preserved. Each span is a new trace natively; the IDs seen in Dart are not the native IDs |
OTelAPI.loggerProvider().getLogger(...).emit | A log at info, warning or error by severity number. attributes, eventName and timestamps are dropped |
Use Sophonz.instance.startSpan(parent:) when the span hierarchy matters.
Network requests
SophonzHttpClient and SophonzInterceptor record requests automatically. Both are described in Networking.
| Signature | Description |
|---|---|
SophonzHttpClient({http.Client? internalClient}) | An http.BaseClient that records every request and adds traceparent |
void recordNetworkRequest(SophonzNetworkRequest request) | Records a request made some other way |
SophonzNetworkRequest.fromCompletedRequest({required String url, required HttpMethod httpMethod, required int startTime, required int endTime, required int bytesSent, required int bytesReceived, required int statusCode, String? traceId, String? w3cTraceparent}) | A request that got a response |
SophonzNetworkRequest.fromIncompleteRequest({required String url, required HttpMethod httpMethod, required int startTime, required int endTime, required String errorDetails, String? traceId, String? w3cTraceparent}) | A request that got no response |
Future<String?> generateW3cTraceparent(String? traceId, String? spanId) | A traceparent value. Android ignores both arguments and generates one. iOS formats the IDs given, or random IDs when either is null |
HttpMethod is get, post, put, delete, patch or other. On Android a request recorded with other is dropped.
W3cTraceContext
| Signature | Description |
|---|---|
static String? fromSpanContext(SpanContext spanContext) | Formats a traceparent from an OpenTelemetry span context. null if invalid |
static SpanContext? extract(String? header) | Parses a traceparent into a remote span context. null if malformed |
static Future<void> injectCurrent(Map<String, String> headers) | Adds traceparent for the current OpenTelemetry span, asking the native SDK first |
static void injectCurrentSync(Map<String, dynamic> headers) | Adds traceparent for the current OpenTelemetry span, formatted in Dart |
The inject methods do nothing when no span is current.
Views
The navigation observers call these for you. Call them directly for screens that are not routes, such as tabs. See Navigation.
| Signature | Description |
|---|---|
void startView(String name) | Starts a view |
void endView(String name) | Ends the view started with that name |
| Signature | Description |
|---|---|
SophonzNavigationObserver({SophonzRouteSettingsExtractor? routeSettingsExtractor, SophonzScreenLoadConfig screenLoadConfig}) | NavigatorObserver for Navigator and MaterialApp |
SophonzGoRouterObserver({GoRouter? router, SophonzRouteSettingsExtractor? routeSettingsExtractor, SophonzScreenLoadConfig screenLoadConfig}) | go_router observer. With router, call dispose() when done |
const SophonzScreenLoadConfig({Duration recencyThreshold = const Duration(seconds: 1)}) | Screen-load span timing |
typedef SophonzRouteSettingsExtractor = RouteSettings? Function(Route<dynamic> route) | Returns the settings to record, or null to skip |
Users
Sophonz.instance.setUserIdentifier('agent-10482');
Sophonz.instance.addUserPersona('beta-tester');| Signature | Android | iOS |
|---|---|---|
void setUserIdentifier(String id), void clearUserIdentifier() | yes | yes |
void addUserPersona(String persona), void clearUserPersona(String persona), void clearAllUserPersonas() | yes | yes, for the process lifespan |
void setUserAsPayer(), void clearUserAsPayer() | yes | yes |
void setUserName(String name), void clearUserName() | yes | ignored |
void setUserEmail(String email), void clearUserEmail() | yes | ignored |
setUserAsPayer adds the persona payer. On iOS, personas are cleared when the process ends, so set them again after launch, for example right after sign-in state is restored.
Prefer an opaque identifier to a name or email. iOS does not record name or email at all.
Sessions
| Signature | Description |
|---|---|
Future<String?> getCurrentSessionId() | The current session ID: 32 lowercase hex characters, or null before a session exists |
void addSessionProperty(String key, String value, {bool permanent = false}) | A property on the current session, or on every later session when permanent is true |
void removeSessionProperty(String key) | Removes the property whatever its lifespan |
void endSession({bool clearUserInfo = true}) | Ends the session and starts a new one. With clearUserInfo, clears the identifier and personas first, and on Android the name and email as well |
NOTE — Ending sessions on iOS is rate-limited
The Apple SDK accepts one endSession per 5 seconds and ignores the rest. Use it for apps that stay in the foreground for a long time, such as kiosks, not per screen.
If you forward the session ID somewhere else, such as a backend header, send it exactly as returned. The backend rejects a whole batch whose session.id is not 32 lowercase hex characters.
Exporters
| Signature | Description |
|---|---|
void addSpanExporter({required String endpoint, List<Map<String, String>>? headers, int? timeoutSeconds}) | An additional OTLP/HTTP span exporter. Android only; call before start |
void addLogRecordExporter({required String endpoint, List<Map<String, String>>? headers, int? timeoutSeconds}) | An additional OTLP/HTTP log exporter. Android only; call before start |
SophonzTracerProvider get tracerProvider | The registered tracer provider. Throws StateError before start or an exporter call |
SophonzLoggerProvider get loggerProvider | The registered logger provider. Same condition |
These export in addition to Sophonz. See Configuration for the timing constraint.
Testing
Replace Sophonz.instance in widget and unit tests with debugSophonzOverride, which is marked @visibleForTesting.
import 'package:mocktail/mocktail.dart';
import 'package:sophonz/sophonz.dart';
class MockSophonz extends Mock implements Sophonz {}
void main() {
late MockSophonz sophonz;
setUp(() {
sophonz = MockSophonz();
debugSophonzOverride = sophonz;
});
tearDown(() => debugSophonzOverride = null);
testWidgets('logs a breadcrumb on pay', (tester) async {
await tester.pumpWidget(const PayButton());
await tester.tap(find.text('Pay'));
verify(() => sophonz.addBreadcrumb('Tapped pay')).called(1);
});
}Without an override, calls in tests are dropped because no native SDK is attached.
SophonzSamples in package:sophonz/sophonz_samples.dart triggers errors, a native crash, an ANR (Android) and a signal (iOS) for testing a build. See Instrumentation.