Examples

A complete Flutter app setup with Sophonz — pubspec, native files, the main.dart start sequence, Dio with traceparent, go_router, a span around a screen load, handled errors, and user and session context.

This page puts the pieces together in one small shop app: an order list and an order detail screen, served by an API over Dio, with go_router navigation. Each section is a file you can adapt. The SDK repository's sophonz/example and sophonz_dio/example apps exercise the same APIs one screen at a time.

Project files

FilePurposeDetails
pubspec.yamlSDK packages from the v0.1.0 tagbelow
android/settings.gradle.kts, android/build.gradle.kts, android/app/build.gradle.ktsGitHub Packages repository and the Sophonz Gradle pluginInstallation
android/app/src/main/sophonz-config.jsonCollector, service key, app_framework: flutterConfiguration
android/app/src/main/kotlin/.../MainApplication.ktSophonz.start(this)Installation
ios/PodfileSophonzIO git sourceInstallation
ios/Sophonz-Info.plistCollector, service keyConfiguration
ios/Runner/AppDelegate.swiftSophonz.start(options:)Installation
lib/main.dart, lib/api.dart, lib/router.dart, lib/order_page.dart, lib/account.dartDart setupbelow

pubspec.yaml

pubspec.yaml
name: shop
publish_to: none
version: 1.4.0+12
 
environment:
  sdk: ">=3.4.0 <4.0.0"
  flutter: ">=3.22.0"
 
dependencies:
  flutter:
    sdk: flutter
  dio: ^5.4.0
  go_router: ^14.0.0 # sophonz_go_router supports go_router below 16
  sophonz:
    git: {url: git@github.com:sophonz-labs/sophonz-flutter-sdk.git, path: sophonz, ref: v0.1.0}
  sophonz_dio:
    git: {url: git@github.com:sophonz-labs/sophonz-flutter-sdk.git, path: sophonz_dio, ref: v0.1.0}
  sophonz_go_router:
    git: {url: git@github.com:sophonz-labs/sophonz-flutter-sdk.git, path: sophonz_go_router, ref: v0.1.0}
  sophonz_platform_interface:
    git: {url: git@github.com:sophonz-labs/sophonz-flutter-sdk.git, path: sophonz_platform_interface, ref: v0.1.0}
 
dependency_overrides:
  sophonz:
    git: {url: git@github.com:sophonz-labs/sophonz-flutter-sdk.git, path: sophonz, ref: v0.1.0}
  sophonz_platform_interface:
    git: {url: git@github.com:sophonz-labs/sophonz-flutter-sdk.git, path: sophonz_platform_interface, ref: v0.1.0}

sophonz_platform_interface is listed because order_page.dart imports ErrorCode from it. The overrides are explained in Installation.

main.dart

lib/main.dart
import 'package:flutter/material.dart';
import 'package:sophonz/sophonz.dart';
 
import 'account.dart';
import 'router.dart';
 
Future<void> main() async {
  // The native SDK is already running: MainApplication (Android) and AppDelegate (iOS) started it.
  await Sophonz.instance.start(action: () async {
    // Inside action, the SDK is attached and errors from here on are captured.
    Sophonz.instance.addSessionProperty(
      'app.flavor',
      const String.fromEnvironment('FLAVOR', defaultValue: 'production'),
    );
 
    final account = await Account.restore();
    if (account != null) onSignedIn(account);
 
    runApp(const ShopApp());
  });
}
 
class ShopApp extends StatelessWidget {
  const ShopApp({super.key});
 
  @override
  Widget build(BuildContext context) {
    return MaterialApp.router(title: 'Shop', routerConfig: router);
  }
}

The order matters: start attaches to the native SDK before action runs, so the session property and user identifier set inside action are not dropped.

api.dart

One Dio instance for the app. TraceparentInterceptor sends a traceparent to the app's own API so its traces join the requests; SophonzInterceptor records every request.

lib/api.dart
import 'package:dio/dio.dart';
import 'package:sophonz/sophonz.dart';
import 'package:sophonz_dio/sophonz_dio.dart';
 
const _apiHost = 'api.example.com';
 
final Dio api = Dio(
  BaseOptions(
    baseUrl: 'https://$_apiHost',
    connectTimeout: const Duration(seconds: 10),
    receiveTimeout: const Duration(seconds: 20),
  ),
)..interceptors.addAll([
    TraceparentInterceptor({_apiHost}),
    SophonzInterceptor(),
  ]);
 
/// Adds a traceparent to requests for [hosts] before SophonzInterceptor records them.
class TraceparentInterceptor extends Interceptor {
  TraceparentInterceptor(this.hosts);
 
  final Set<String> hosts;
 
  @override
  void onRequest(RequestOptions options, RequestInterceptorHandler handler) async {
    if (hosts.contains(options.uri.host) &&
        !options.headers.containsKey('traceparent')) {
      final value = await Sophonz.instance.generateW3cTraceparent(null, null);
      if (value != null) options.headers['traceparent'] = value;
    }
    handler.next(options);
  }
}

Why the extra interceptor is needed is explained in Networking.

router.dart

The app has no shell routes, so the observer goes in observers. With StatefulShellRoute, use router mode instead (Navigation).

lib/router.dart
import 'package:go_router/go_router.dart';
import 'package:sophonz_go_router/sophonz_go_router.dart';
 
import 'order_list_page.dart';
import 'order_page.dart';
 
final GoRouter router = GoRouter(
  observers: [SophonzGoRouterObserver()],
  routes: [
    GoRoute(
      path: '/',
      name: 'orders',
      builder: (context, state) => const OrderListPage(),
      routes: [
        GoRoute(
          path: 'orders/:id',
          name: 'order',
          builder: (context, state) => OrderPage(id: state.pathParameters['id']!),
        ),
      ],
    ),
  ],
);

After the first run, look at the view and screen-load span names in Sophonz. If they contain order IDs, normalize them with routeSettingsExtractor as shown in Navigation.

A span around a screen load

The screen-load span from the observer ends at the first frame. This span covers what the user actually waits for: the order arriving from the API.

lib/order_page.dart
import 'package:dio/dio.dart';
import 'package:flutter/material.dart';
import 'package:sophonz/sophonz.dart';
import 'package:sophonz_platform_interface/sophonz_platform_interface.dart' show ErrorCode;
 
import 'api.dart';
import 'order.dart';
 
class OrderPage extends StatefulWidget {
  const OrderPage({super.key, required this.id});
 
  final String id;
 
  @override
  State<OrderPage> createState() => _OrderPageState();
}
 
class _OrderPageState extends State<OrderPage> {
  late final Future<Order> _order = _load();
 
  Future<Order> _load() async {
    final span = await Sophonz.instance.startSpan('order-detail-load');
    await span?.addAttribute('order.id', widget.id);
    try {
      final response = await api.get<Map<String, dynamic>>('/orders/${widget.id}');
      final order = Order.fromJson(response.data!);
      await span?.addAttribute('order.item_count', '${order.items.length}');
      await span?.stop();
      return order;
    } catch (error, stack) {
      await span?.stop(errorCode: ErrorCode.failure);
      Sophonz.instance.logHandledDartError(error, stack);
      rethrow;
    }
  }
 
  Future<void> _pay(Order order) async {
    Sophonz.instance.addBreadcrumb('Tapped pay');
    try {
      await api.post<void>('/orders/${order.id}/payment');
      Sophonz.instance.logInfo('Payment completed', properties: {'order.id': order.id});
    } on DioException catch (error, stack) {
      Sophonz.instance.logError(
        'Payment failed',
        properties: {
          'order.id': order.id,
          'http.status_code': '${error.response?.statusCode ?? 0}',
        },
      );
      Sophonz.instance.logHandledDartError(error, stack);
      if (mounted) {
        ScaffoldMessenger.of(context).showSnackBar(
          const SnackBar(content: Text('Payment failed. Try again.')),
        );
      }
    }
  }
 
  @override
  Widget build(BuildContext context) {
    return FutureBuilder<Order>(
      future: _order,
      builder: (context, snapshot) {
        final order = snapshot.data;
        if (snapshot.hasError) return const Scaffold(body: Center(child: Text('Could not load the order')));
        if (order == null) return const Scaffold(body: Center(child: CircularProgressIndicator()));
        return Scaffold(
          appBar: AppBar(title: Text('Order ${order.id}')),
          body: OrderSummary(order: order),
          bottomNavigationBar: FilledButton(
            onPressed: () => _pay(order),
            child: const Text('Pay'),
          ),
        );
      },
    );
  }
}

The span name is fixed and the order ID is an attribute, so every order detail load shares one span name.

What arrives for one visit to this screen:

RecordSource
View and screen-load span for the routeSophonzGoRouterObserver
order-detail-load span with order.id and order.item_countstartSpan above
GET /orders/<id> network span with the traceparent sentSophonzInterceptor
The backend's server spans in the same trace as that headerthe backend SDK
On failure: the span marked failed and a handled error logstop(errorCode:), logHandledDartError

account.dart

User identity and sign-out. endSession clears the identifier and personas before the new session starts, so the next user's session does not carry them.

lib/account.dart
import 'package:sophonz/sophonz.dart';
 
void onSignedIn(Account account) {
  // An opaque ID, not an email address.
  Sophonz.instance.setUserIdentifier(account.id);
  if (account.hasSubscription) {
    Sophonz.instance.setUserAsPayer();
  }
}
 
void onSignedOut() {
  Sophonz.instance.endSession(); // clearUserInfo defaults to true
}

On iOS, personas last only for the process, which is why main.dart calls onSignedIn again after restoring the account on every launch.

Errors that need no code

With start(action: ...) in place, these are recorded without anything else in the app:

// Uncaught async error: recorded through PlatformDispatcher.onError.
onPressed: () async {
  await api.get<void>('/does-not-exist'); // DioException, not caught
},
 
// Framework error: recorded through FlutterError.onError.
Row(children: [Text('a very long label ' * 20)]), // RenderFlex overflow

A DioException thrown here is recorded twice in different forms: as a network span by SophonzInterceptor and as an unhandled error log.

Verifying

  1. Run on a device in debug mode and look for Sophonz Flutter SDK attached to host SDK successfully.
  2. Open an order, tap Pay, then send the app to the background.
  3. In Sophonz, find the session. It should hold the route views, the order-detail-load span, the GET and POST network spans, the breadcrumb and the payment log.
  4. Open the GET network span and follow its trace to the backend's spans.

Next