Skip to content
Last9
Book demo

Flutter RUM SDK

Install and configure the Last9 Flutter RUM SDK. Dart plugin over native Android and iOS SDKs, CDN-hosted tar.gz, auto-instruments HttpClient, NavigatorObserver, errors, ANRs.

Real User Monitoring for Flutter apps. Automatic instrumentation for sessions, views, network requests, errors, and resource metrics via OpenTelemetry. ANR detection is available on Android only.

The Flutter SDK is a Dart plugin over the Android and iOS native SDKs. Both platform CDN repos must be configured so native dependencies resolve.

Prerequisites

  • Flutter >= 3.10.0
  • Dart SDK >= 3.0.0
  • iOS 15.1+
  • Android minSdk 21 (Android 5.0+)
  • Native dependencies (each plugin version pins the native SDKs of the same version):
    • Plugin 1.14.0 (latest versioned release):
      • Android: io.last9:rum-android:1.14.0 (resolved from CDN Maven)
      • iOS: Last9RUM 1.14.0 (resolved from CDN podspec)
    • Plugin 1.8.0 (stable/v1 channel):
      • Android: io.last9:rum-android:1.8.0
      • iOS: Last9RUM 1.8.0

Create Client Monitoring Tokens

Create one Client token per platform — do not combine Android and iOS origins on a single token. Each build uses the native SDK for that platform, so separate tokens keep origin scoping, rotation, and access control aligned with Android and iOS setup.

  1. Open Last9 → Settings → Ingestion Tokens
  2. Click Create Token → choose type Client → create an Android token with allowed origin android://com.yourcompany.yourapp (your app’s exact package name). Copy the token.
  3. Create a second Client token for iOS with allowed origin ios://com.yourcompany.yourapp (your app’s exact bundle ID). Copy the token.
  4. Copy the OTLP endpoint URL (the same URL is used for both platforms)

CDN artifacts

ArtifactStable URLVersioned URL
Tarballhttps://cdn.last9.io/rum-sdk/flutter/builds/stable/v1/last9_rum_flutter.tar.gzhttps://cdn.last9.io/rum-sdk/flutter/builds/1.14.0/last9_rum_flutter-1.14.0.tar.gz
Checksumhttps://cdn.last9.io/rum-sdk/flutter/builds/stable/v1/last9_rum_flutter.tar.gz.sha256https://cdn.last9.io/rum-sdk/flutter/builds/1.14.0/last9_rum_flutter-1.14.0.tar.gz.sha256

The major-pinned stable/v1 channel currently serves Flutter RUM SDK 1.8.0. The latest versioned release is 1.14.0; staging builds use the -alpha.<run_number> suffix and explicit versioned URLs.

Installation

  1. Download, verify, and extract the SDK

    curl -L -o last9_rum_flutter.tar.gz \
    "https://cdn.last9.io/rum-sdk/flutter/builds/1.14.0/last9_rum_flutter-1.14.0.tar.gz"
    # Verify checksum
    EXPECTED=$(curl -sL "https://cdn.last9.io/rum-sdk/flutter/builds/1.14.0/last9_rum_flutter-1.14.0.tar.gz.sha256")
    ACTUAL=$(shasum -a 256 last9_rum_flutter.tar.gz | awk '{print $1}')
    [ "$EXPECTED" = "$ACTUAL" ] && echo "OK" || echo "CHECKSUM MISMATCH"
    # Extract into vendor/
    mkdir -p vendor
    tar xzf last9_rum_flutter.tar.gz -C vendor/
    rm last9_rum_flutter.tar.gz
  2. Add as a path dependency

    In pubspec.yaml:

    dependencies:
    last9_rum_flutter:
    path: vendor/flutter

    Then:

    flutter pub get
  3. Android — add the CDN Maven repository

    Gradle repositories are not transitive — the Flutter plugin cannot inject this repo into your app. Your consumer app must declare it so io.last9:rum-android resolves on the app’s classpath.

    dependencyResolutionManagement {
    repositories {
    google()
    mavenCentral()
    maven { url = uri("https://cdn.last9.io/rum-sdk/android/maven/") }
    }
    }
  4. iOS — add the Last9RUM podspec

    In ios/Podfile, inside the target 'Runner' block:

    target 'Runner' do
    use_frameworks!
    pod 'Last9RUM', :podspec => 'https://cdn.last9.io/rum-sdk/ios/builds/1.14.0/Last9RUM.podspec'
    flutter_install_all_ios_pods File.dirname(File.realpath(__FILE__))
    end

    The podspec version must match the Last9RUM version that the plugin pins. Plugin 1.14.0 pins Last9RUM 1.14.0. If you use the stable/v1 tarball (plugin 1.8.0), use https://cdn.last9.io/rum-sdk/ios/builds/1.8.0/Last9RUM.podspec.

    Then:

    cd ios && pod install
  5. Initialize the SDK

    import 'dart:io' show Platform;
    import 'package:flutter/widgets.dart';
    import 'package:last9_rum_flutter/last9_rum_flutter.dart';
    void main() async {
    WidgetsFlutterBinding.ensureInitialized();
    final isIos = Platform.isIOS;
    await L9Rum.initialize(L9RumConfig(
    baseUrl: 'https://otlp-ext-aps1.last9.io/v1/otlp/organizations/<org>',
    // Use the platform-matching token and origin pair — see
    // "Create Client Monitoring Tokens" above.
    origin: isIos
    ? 'ios://com.yourcompany.yourapp'
    : 'android://com.yourcompany.yourapp',
    clientToken: isIos ? 'your-ios-client-token' : 'your-android-client-token',
    serviceName: 'my-flutter-app',
    serviceVersion: '1.0.0',
    deploymentEnvironment: 'production',
    ));
    runApp(const MyApp());
    }

Configuration

final L9RumConfig config = L9RumConfig(
// --- Required ---------------------------------------------------------
baseUrl: 'https://otlp-ext-aps1.last9.io/v1/otlp/organizations/<org>',
clientToken: Platform.isIOS
? 'your-ios-client-token'
: 'your-android-client-token',
serviceName: 'my-flutter-app',
serviceVersion: '1.0.0',
deploymentEnvironment: 'production',
// --- Optional ---------------------------------------------------------
// Origin sent as X-LAST9-ORIGIN header. Required for client_monitoring
// tokens. Must match the origin on the platform's Client token —
// android://<package> on Android, ios://<bundle-id> on iOS. Pass the
// matching clientToken for the same platform. Needs `import 'dart:io' show
// Platform` as shown in the Installation section above.
origin: Platform.isIOS
? 'ios://com.yourcompany.yourapp'
: 'android://com.yourcompany.yourapp',
// Specific build identifier (maps to app.build_id)
appBuildId: '1.0.0-build-42',
// Optional override for the app.installation.id resource attribute.
// The Client-ID header always uses the native SDK-generated per-install UUID.
appInstallationId: null,
// Session sampling rate: 0-100 (percentage). 100 = sample everything.
sampleRate: 100,
// Print debug logs to native console
debugLogs: false,
// Automatically instrument HTTP requests
networkInstrumentation: true,
// Automatically capture unhandled Dart errors
errorInstrumentation: true,
// Max spans per export batch
maxExportBatchSize: 100,
// How long native batch processors wait before flushing queued spans/logs (ms).
// Omit: 5000 in production, 1000 when debugLogs is true (`v1.4.0+`).
scheduleDelayMs: null,
// When false, native Activity/ViewController auto-tracking no longer opens
// or closes view spans — the app owns view names (`v1.5.0+`).
autoViewTrackingEnabled: true,
// Export timeout in milliseconds
exportTimeoutMs: 30000,
// ANR detection (Android only)
anrDetectionEnabled: true,
anrThresholdMs: 5000,
// Periodically sample memory and CPU
resourceMonitoringEnabled: true,
resourceSamplingIntervalMs: 30000,
// Setting this to true will hide network requests (and their
// DNS/TCP/TLS/TTFB phase child spans) from the Last9 dashboard's
// Sessions → APIs tab. Each request would get its own traceId
// instead of sharing the current view's traceId, and that tab
// only fetches spans that share the View's traceId. Keep this
// false unless you specifically need per-request trace isolation.
isolateTracePerRequest: false,
// Custom resource attributes added to every span
resourceAttributes: <String, String>{
'app.platform': 'flutter',
},
// Fine-grained network ignore rules. contains() uses substring matching;
// regex() uses regex search semantics. Matched URLs are dropped before
// span creation.
ignorePatterns: L9NetworkIgnorePatterns(
fullUrl: <L9UrlPattern>[
L9UrlPattern.contains('https://cdn.example.com'),
L9UrlPattern.regex(RegExp(r'^https://.*\.example\.com', caseSensitive: false)),
],
pathname: <L9UrlPattern>[
L9UrlPattern.contains('.pdf'),
L9UrlPattern.contains('.jpg'),
L9UrlPattern.regex(RegExp(r'^/internal/metrics')),
],
hostname: <L9UrlPattern>[
L9UrlPattern.contains('cdn.example.com'),
L9UrlPattern.regex(RegExp(r'(^|\.)assets\.example\.com$', caseSensitive: false)),
],
),
// 'preserve' (default): keep traceparent on ignored requests.
// 'strip': remove traceparent from ignored requests.
propagationMode: L9PropagationMode.preserve,
// W3C Baggage propagation on outgoing requests
baggage: L9BaggageConfig(
enabled: false,
allowedKeys: <String>['session.id', 'user.id'],
maxTotalBytes: 8192,
warnAtPercentage: 80,
),
// Dart hook that renames network spans or adds attributes. The request URL
// does not change. Runs for dart:io, Dio, and L9GqlLink requests (`v1.9.0+`).
// See "Network span names".
networkSpanHook: null,
// Path rewrite rules for the default network span name. Sent to native, so
// they also apply to requests that native code makes (`v1.9.0+`).
networkSpanNameRules: <L9NetworkSpanNameRule>[],
// Opt-in GraphQL variable and error detail. Off by default (`v1.12.0+`).
// See "GraphQL detail (opt-in)".
graphqlDetail: const L9GraphQLDetailConfig(),
// Called after each native trace export (onExport) or each failed export
// (onError) with an L9ExportResult. Not sent to native. debugLogs does not
// control them (`v1.14.0+`). See "Check the connection from code".
onExport: null,
onError: null,
// Auto-load Last9 Browser RUM into WebViews that you pass to
// L9Rum.instrumentWebView (`v1.11.1+`). Enable only for trusted content.
webViewAutoLoadBrowserRum: false,
);

The native layers send an SDK-generated per-install UUID as the ingestion Client-ID header, not serviceName, so devices do not share one rate-limit bucket. appInstallationId only overrides the app.installation.id resource attribute. It does not override the Client-ID header, so the header and the resource attribute can differ when you set appInstallationId manually.

From 1.10.0, the resource of all telemetry from the plugin carries telemetry.distro.name=last9-rum-flutter and telemetry.distro.version=<plugin version>. Use these attributes to find Flutter traffic and its plugin version. No configuration is necessary.

Per-view performance vitals (v1.7.0+)

When resourceMonitoringEnabled is on (the default), the native SDKs add per-view frame and memory vitals to each View span. Flutter inherits them with no Dart changes, so you can find which screens janked or ran hot without extra instrumentation.

AttributeTypeDescription
view.refresh_rate_averagefloatAverage refresh rate over the view, normalized to 0–60 Hz so 60 Hz and 120 Hz devices compare directly
view.refresh_rate_minfloatLowest refresh rate seen during the view (the worst dip)
view.frame.slowintSlow frames — inter-tick interval above 1.5× the display refresh period
view.frame.frozenintFrozen frames — longer than 700 ms
view.memory_averageintAverage resident memory bytes over the view
view.memory_maxintPeak resident memory bytes during the view
process.cpu.usagefloatProcess CPU usage averaged over the view
  • Frame timing and memory are sampled by the native Android and iOS SDKs. Frame tracking pauses while the app is backgrounded, so a background gap is never counted as a frozen frame.
  • No Dart API change: the vitals ride on the existing resourceMonitoringEnabled flag. Set it to false to turn off resource sampling and these vitals together.

Where to see it: open a session in the Last9 RUM UI, select a view on the timeline, and check the Attributes tab. Views that carry these attributes show a MOBILE VITALS section with rows such as Refresh Rate (avg), Slow Frames, Frozen Frames, Memory (avg), and CPU Usage, formatted with units. Web views are unaffected.

MOBILE VITALS section in the view Attributes tab

API reference

Automatic view tracking

Attach L9NavigationObserver to your MaterialApp or CupertinoApp:

MaterialApp(
navigatorObservers: <NavigatorObserver>[L9NavigationObserver()],
// ...
);

Network ignore patterns

Skip noisy URLs before span creation by matching against full URL, pathname, or hostname. L9UrlPattern.contains() uses substring matching; L9UrlPattern.regex() uses regex search semantics.

await L9Rum.initialize(L9RumConfig(
// ...required config
ignorePatterns: L9NetworkIgnorePatterns(
fullUrl: <L9UrlPattern>[
L9UrlPattern.contains('https://cdn.example.com'),
L9UrlPattern.regex(RegExp(r'^https://.*\.example\.com', caseSensitive: false)),
],
pathname: <L9UrlPattern>[
L9UrlPattern.contains('.pdf'),
L9UrlPattern.contains('.jpg'),
L9UrlPattern.regex(RegExp(r'^/internal/metrics')),
],
hostname: <L9UrlPattern>[
L9UrlPattern.contains('cdn.example.com'),
L9UrlPattern.regex(RegExp(r'(^|\.)assets\.example\.com$', caseSensitive: false)),
],
),
// preserve (default): keep traceparent on ignored requests.
// strip: remove traceparent from ignored requests.
propagationMode: L9PropagationMode.strip,
));

Network span names

From 1.9.0, you can rename network spans or add attributes without a change to the request URL. url.full keeps the real URL. ignorePatterns only drops spans; use these options to put high-cardinality paths into one span name.

networkSpanHook is a Dart function. It gets an L9NetworkSpanDetails (method, url, path, requestBody, graphqlOperationName, graphqlOperationType) and returns an L9NetworkSpanCustomization (spanName, attributes), or null to keep the default.

await L9Rum.initialize(L9RumConfig(
// ...required config
networkSpanHook: (L9NetworkSpanDetails details) {
final path = details.path.replaceAll(RegExp(r'/orders/[A-Z0-9]{12}'), '/orders/{orderId}');
if (path == details.path) return null;
return L9NetworkSpanCustomization(
spanName: '${details.method} $path',
attributes: <String, String>{'app.route': '/orders/{orderId}'},
);
},
));
  • The hook runs in Dart inside L9Rum.startNetworkSpan, so dart:io, Dio, and L9GqlLink requests all see it. The SDK parses the GraphQL operation before the hook runs.
  • An explicit spanName argument to startNetworkSpan wins over the hook.
  • The hook does not run for URLs that ignorePatterns drops or for the SDK endpoint.
  • If the hook throws, the span keeps its default name. The SDK logs the error through dart:developer (name L9Rum).
  • Native code cannot call the Dart hook. Requests that native code makes (for example iOS URLSession.shared traffic from a native plugin) and requests through L9Rum.instrumentedHttpClient() do not run it. Use networkSpanNameRules for these requests.

networkSpanNameRules is a list of path rewrite rules for the default span name. Each L9NetworkSpanNameRule(match: L9UrlPattern, replacement) replaces every match in the request path, in list order, before the SDK folds the path. L9UrlPattern.regex replacements can use $1-style group references. The SDK sends the rules to native, so they apply to Dart requests and to requests that native code makes.

await L9Rum.initialize(L9RumConfig(
// ...required config
networkSpanNameRules: <L9NetworkSpanNameRule>[
L9NetworkSpanNameRule(
match: L9UrlPattern.regex(RegExp(r'/carts/[A-Za-z0-9]{20}')),
replacement: '/carts/{cartId}',
),
],
));
// GET https://api.example.com/v1/carts/a1B2c3D4e5F6g7H8i9J0 -> span "GET /v1/carts/{cartId}"

networkSpanHook and an explicit spanName win over the rules. The rules do not change GraphQL span names.

Network phase child spans

Network instrumentation emits child spans for individual HTTP phases where native timing hooks are available:

Child spanWhat it measures
dnsDNS lookup duration
tcp_connectTCP connection establishment
tls_handshakeTLS negotiation
ttfbTime from request sent to first response byte

No SDK config change is required. The native Android and iOS layers use OkHttp EventListener and URLSession task metrics respectively.

From 1.11.2, the SDK emits a phase child span only when it observes the real timing. When a phase is not available (for example DNS, TCP, and TLS on a reused connection), the SDK omits that phase. It does not emit a zero-duration placeholder. On 1.11.1 and earlier, the SDK emitted zero-duration child spans with l9rum.network.phase.skipped=true for these phases.

Real network phase timings

From 1.11.2, L9Rum.instrumentedHttpClient() returns an opt-in package:http Client. On iOS and Android, the native transport of the SDK runs the request (iOS URLSession, Android instrumented OkHttp). The SDK then records the real dns, tcp_connect, tls_handshake, and ttfb child spans below the request span. Call it after L9Rum.initialize(...):

await L9Rum.initialize(L9RumConfig(/* ... */));
final client = L9Rum.instrumentedHttpClient();
final response = await client.get(Uri.parse('https://api.example.com/users'));
  • On other platforms, or if the SDK cannot make the native client, the method returns the standard dart:io instrumented client. That client records the request span with no phase child spans.
  • The native transport reads at most 10 MB of the response body. A larger response fails with a NATIVE_HTTP_RESPONSE_TOO_LARGE error. For large downloads or server-sent events, use the default dart:io client.
  • followRedirects: false has no effect. The native client follows redirects. reasonPhrase on the response is approximate.
  • When networkInstrumentation is false, the client still works. The SDK does not trace the request.
  • After shutdown() and a new initialize(), the client uses the new SDK instance.
  • Do not also add L9DioInterceptor or manual span code to requests through this client. The SDK then records the request two times.
  • Dio’s default adapter uses dart:io. To get real phase timings for Dio, use an http.Client-based Dio adapter with L9Rum.instrumentedHttpClient().

HTTP client instrumentation

When networkInstrumentation is true, the SDK installs a dart:io HttpOverrides that wraps the default HttpClient. Requests made through the http package and dio go through HttpClient under the hood and are traced automatically — no extra setup needed.

From 1.3.0, REST network span names fold fully-numeric and UUID path segments to ? (for example GET /workspaces/1 becomes GET /workspaces/?). GraphQL span names are unaffected. The raw URL is retained on the native span. To fold other dynamic segments, see Network span names.

From 1.9.0, network spans that native code intercepts also carry the legacy http.method, http.url, and http.status_code attributes, so they show in the RUM Network endpoint view.

From 1.12.0, when Dio uses the HttpClient that the SDK wraps and L9DioInterceptor is on the Dio client, only the Dio interceptor records the network span. The SDK does not record the request two times. Other dart:io requests stay instrumented, also while a Dio request is in flight.

GraphQL network observability

GraphQL enrichment (Layer 1) is automatic. L9HttpClient captures the request body and the SDK taps the response body to detect GraphQL errors before ending the span:

Span attributeExampleNotes
Span nameGraphQL: "GetUserPreferences" queryRenamed to a descriptive name
graphql.operation.nameGetUserPreferencesquery, mutation, or subscription name
graphql.operation.typequeryOperation type
error.typeGraphQLErrorSet when the response contains a non-empty errors[]
graphql.error.countnumberNumber of entries in the errors[] array

GraphQL transport variants

From 1.13.0, the native SDKs name the span and count the GraphQL errors for these transport variants:

  • Batches: a JSON array of operations makes one network span. A batch of one operation is named like that operation. A batch of more than one operation is named GraphQL: batch and gets graphql.batch.size (the full operation count) and graphql.batch.operation.names (the first 10 distinct named operations, in request order; anonymous operations are not included). Different batches share the GraphQL: batch row; open a trace to see its operation names.
  • Persisted queries: a request with an extensions.persistedQuery object (for example Apollo APQ) gets graphql.persisted_query=true and graphql.persisted_query.id (the hash, only when it matches ^[A-Za-z0-9_-]{1,128}$). The hash is never part of the span name. A request that sends only the hash keeps the default span name.
  • GET: a GET to a URL path that contains graphql reads query, operationName, and extensions from the query string. networkSpanHook also gets the operation of a GET request in graphqlOperationName / graphqlOperationType.
  • Errors: the SDK inspects only 2xx responses, and only the first 64 KiB. It counts errors, @defer / @stream errors (incremental[].errors, completed[].errors), a multipart subscription payload, each element of a batch response, and each part of a multipart/mixed response.

Layer 2 — Dio and gql interceptors (opt-in)

For richer GraphQL telemetry, wire the client-specific integration:

  • L9DioInterceptor — add to a Dio client’s interceptor chain. From 1.13.0, it sends at most 64 KiB of the response body to native (native reads only that much). It does not send a ResponseType.stream body.
  • L9GqlLink — a link for the gql / graphql packages. It requires endpointUrl and suppresses the duplicate dart:io transport span while forwarding to HttpLink. From 1.12.0, it sends the request variables and the reduced errors[] (message, extensions.code, path, locations) to native. The graphqlDetail option controls which of them become span attributes.
import 'package:dio/dio.dart';
import 'package:last9_rum_flutter/last9_rum_flutter.dart';
final dio = Dio()..interceptors.add(L9DioInterceptor());
import 'package:gql_http_link/gql_http_link.dart';
import 'package:gql_link/gql_link.dart';
import 'package:last9_rum_flutter/last9_rum_flutter.dart';
const endpoint = 'https://api.example.com/graphql';
final link = Link.from(<Link>[
L9GqlLink(endpointUrl: endpoint),
HttpLink(endpoint),
]);

From 1.9.1, when the consumer cancels a GraphQL operation, L9GqlLink releases the transport span suppression at once. If the cancel occurs before the native span starts, the link does not send the request and ends the span. If the cancel occurs while the link waits for a response, the link cancels the downstream subscription and ends the span with GraphQL link disposed before response. On 1.9.0 and earlier, a downstream that never responded kept dart:io instrumentation off for the full app.

GraphQL detail (opt-in)

From 1.12.0, you can export selected variables and the GraphQL error detail. Both are off by default. Set them with the graphqlDetail option (L9GraphQLDetailConfig) on L9RumConfig. The native SDKs apply the policy, so it is the same for dart:io, Dio, L9GqlLink, and native traffic. The field names are the same in the Web, Android, iOS, and React Native SDKs.

await L9Rum.initialize(L9RumConfig(
// ...required config
graphqlDetail: const L9GraphQLDetailConfig(
captureVariables: true,
variableAllowList: <String>['tenantId', 'input.page.limit', 'items.0.id'],
extraSensitivePatterns: <String>['email'],
captureErrorDetails: true,
),
));
OptionTypeDefaultDescription
captureVariablesboolfalseExport the allow-listed variables
variableAllowListList<String>[]Dot paths to leaf values (tenantId, input.page.limit, items.0.id)
extraSensitivePatternsList<String>[]Extra key patterns to redact, added to the built-in list
maxVariablesint10Max graphql.variables.* attributes per span
maxVariableValueLengthint256Max characters per variable value
captureErrorDetailsboolfalseExport per-error detail
maxErrorsint5Max errors (by index) that get detail attributes
maxErrorFieldLengthint200Max characters of each error field
Span attributeSource
graphql.variables.<entry>The scalar value at the allow-list entry
graphql.error.<i>.messageerrors[i].message
graphql.error.<i>.codeerrors[i].extensions.code
graphql.error.<i>.patherrors[i].path, joined with . (for example user.0.name)
graphql.error.<i>.locationserrors[i].locations as line:column, joined with ,
  • Only string, number, and boolean values are exported. Object, array, and null values are never exported, even when their path is allow-listed.
  • A value is exported as [REDACTED] when any segment of its path contains a sensitive pattern (case-insensitive): password, passwd, secret, token, apikey, api_key, api-key, authorization, credential, cookie, plus extraSensitivePatterns.
  • The query text, the full request body, the response data, error extensions other than code, and HTTP headers are never captured, even with opt-in.
  • On native iOS URLSession traffic, the SDK reads only URLRequest.httpBody. URLSession usually sends the body as a stream, so the SDK does not see the operation and variables there. Error detail still works when the path contains graphql.

Identify a user

await L9Rum.identify(const L9UserInfo(
id: 'user-123',
name: 'Jane',
email: 'jane@example.com',
fullName: 'Jane Doe',
roles: <String>['admin'],
));

Clear user on sign-out

await L9Rum.clearUser();

Capture errors

try {
// risky operation
} catch (error, stackTrace) {
await L9Rum.captureError(
error,
stackTrace: stackTrace,
context: <String, dynamic>{'screen': 'checkout'},
);
}

The SDK normalizes non-Error Dart payloads and bridged native fallback errors, so exception.type stays populated.

Unhandled error forwarding

Flutter’s error surfaces are separate — framework, platform dispatcher, and async zones each need wiring:

void main() async {
WidgetsFlutterBinding.ensureInitialized();
await L9Rum.initialize(config);
// Flutter framework errors
FlutterError.onError = (FlutterErrorDetails details) {
FlutterError.presentError(details);
L9Rum.captureError(details.exception, stackTrace: details.stack);
};
// Platform dispatcher errors
PlatformDispatcher.instance.onError = (Object error, StackTrace stack) {
L9Rum.captureError(error, stackTrace: stack);
return true;
};
// Async errors via zone
runZonedGuarded(
() => runApp(const MyApp()),
(Object error, StackTrace stack) {
L9Rum.captureError(error, stackTrace: stack);
},
);
}

Track views manually

await L9Rum.startView('ProductDetailsScreen');
await L9Rum.setViewName('Product #42');

From 1.5.0, startView never leaves a duplicate native view alongside Activity/ViewController auto-tracking, and setViewName renames the active view in place. Set autoViewTrackingEnabled: false when the app owns all view names.

Custom events

await L9Rum.addEvent('purchase_completed', attributes: <String, dynamic>{
'product_id': '12345',
'amount': 29.99,
});

Each call dual-emits (behavior inherited from the native Android and iOS SDKs):

  • A span event on the active view span, so the event shows up on the view’s timeline in RUM.
  • An OTLP log record carrying event.type=custom, event.name, your attributes, and session.id/user attributes. When a view is active the log is correlated to it via trace.id/span.id/view.id, so you can pivot between the log and the RUM session.

Log emission is unconditional. If no view is active when you call addEvent, the span event is dropped (no view is fabricated to attach it to) but the log is still sent as an orphan, omitting trace.id/span.id/view.id. A custom event never silently vanishes because it fired outside a view.

From 1.5.2, an addEvent fired while a screen is being torn down attaches to that screen (a 1000 ms grace window after the view ends), not the next one. After the window, and whenever no view is current, the OTLP log still correlates to the last view for the rest of the session. A manual startView(...) ends the previous view immediately. Prefer firing screen summaries before teardown (for example in dispose() / a route’s pop callback).

Custom spans

From 1.11.0, time your own operations with L9Rum.recordSpan, L9Rum.startSpan, and L9Rum.endSpan. Custom spans work on Android and iOS. Use a custom span for an operation that you want to count and time. Use addEvent for point-in-time context on a view.

import 'package:last9_rum_flutter/last9_rum_flutter.dart';
Future<void> trackCheckout(DateTime startedAt, DateTime finishedAt) async {
// A finished span: ends now, started 250 ms ago
await L9Rum.recordSpan(
'checkout.validate',
durationMs: 250,
attributes: <String, Object?>{'items': 3},
);
// Or with explicit epoch-ms times
await L9Rum.recordSpan(
'cache.sync',
startTimeMs: startedAt.millisecondsSinceEpoch,
endTimeMs: finishedAt.millisecondsSinceEpoch,
kind: L9SpanKind.client,
);
// A span you end yourself
final String? handle = await L9Rum.startSpan(
'image.decode',
attributes: <String, Object?>{'format': 'webp'},
);
// ... work ...
if (handle != null) await L9Rum.endSpan(handle);
}
  • A custom span is a child of the active view span and carries l9.span.category=custom. With no active view, it is a root span.
  • recordSpan takes exactly one of durationMs or startTimeMs + endTimeMs (epoch ms). Both forms, neither, a partial pair, a negative duration, endTimeMs < startTimeMs, or a blank name throw ArgumentError and emit nothing. recordSpan returns false when the SDK is not initialized.
  • kind is an L9SpanKind: internal (default), client, server, producer, or consumer. The default L9SpanKind.internal feeds the trace_internal_* metrics.
  • Attributes keep String, bool, int, finite double, and List<String> values. The SDK drops other values, NaN, and infinities. At most 64 of your attributes are kept per span, chosen by sorted key.
  • startSpan returns null when the SDK is not initialized or the name is blank. endSpan with an unknown or already-ended handle does nothing.
  • Always call endSpan. A span that is not ended within 5 minutes ends with ERROR status. shutdown() ends open spans.

Global span attributes

await L9Rum.spanAttributes(<String, dynamic>{
'experiment': 'checkout_v2',
'feature_flag': 'new_cart',
});
// Clear
await L9Rum.spanAttributes(null);

Session ID

final String? sessionId = await L9Rum.getSessionId();

From 1.1.9 (native iOS Last9RUM 1.1.9 and Android rum-android:1.1.9), getSessionId() returns a real session id as soon as initialize() completes, and null (never an empty string) when there is no active session. On iOS this closes a window where a read soon after init could race asynchronous session creation and return null or an internal placeholder; Android was already synchronous.

From 1.4.1, backgrounding the app no longer ends the RUM session. Returning within 30 minutes resumes the same session.id. A force-quit or crash backfills Session End on the next cold start (session.end_reason=process_death) and starts a fresh session.

Every span carries session.start_time (epoch ms) alongside session.id, so the backend can read the real start time of a session from any span. When a session rolls over on inactivity timeout or max duration, Session End and session.time_spent use the last recorded activity, so idle and background time is not counted, and the new session keeps session.previous_id. No Dart API change.

Flush pending data

await L9Rum.flush();

Check the connection from code

From 1.14.0, call L9Rum.sendTestEvent() after initialize to confirm that telemetry reaches Last9. The native SDK sends one l9.test_event span at once (not batched) and returns the export result as an L9ExportResult. The method never throws.

import 'package:flutter/foundation.dart';
import 'package:last9_rum_flutter/last9_rum_flutter.dart';
Future<void> checkLast9Connection() async {
final L9ExportResult result = await L9Rum.sendTestEvent();
if (result.ok) {
debugPrint('Last9 RUM is connected: ${result.status}');
} else {
debugPrint('Last9 RUM cannot reach Last9: ${result.status} ${result.error}');
}
}

To monitor each native trace export, set onExport (each export) or onError (failed exports only) in L9RumConfig. The plugin does not send these callbacks to native, and they do not depend on debugLogs. The native plugin reports export results to Dart only when you set one of them.

await L9Rum.initialize(L9RumConfig(
// ...required config
onError: (L9ExportResult result) {
// for example L9ExportResult(ok: false, status: 400, spanCount: 12,
// error: HTTP 400: token origin not allowed)
reportToYourMonitoring(result);
},
));
FieldTypeDescription
okbooltrue when Last9 accepted the export (HTTP 2xx)
statusintHTTP status. 0 when there was no HTTP response (network error, timeout)
spanCountintNumber of spans in the export
errorString?Failure reason, with the Last9 response text when there is one. sendTestEvent also uses not_initialized, session_not_sampled, timeout, and not_supported
  • When the session is not sampled, sendTestEvent sends nothing and returns error: "session_not_sampled". Set sampleRate: 100 while you verify the setup.
  • When the native part of the plugin does not have sendTestEvent, the method returns error: "not_supported".
  • The SDK calls onExport and onError on the platform (UI) isolate. If your callback throws, the SDK logs the error and continues to report exports.

Embedded per-flow lifecycle

For embedded integrations scoped to a single flow, use shutdown() and isActive() (both bridged to the native SDKs) to control the SDK lifecycle:

// Scope RUM to a single flow, then tear it down so the next flow starts clean.
await L9Rum.initialize(config);
// Attributes known only after the flow starts apply to every later span.
await L9Rum.spanAttributes(<String, dynamic>{'tenant.id': 'acme', 'feature.flag': 'beta'});
if (await L9Rum.isActive()) {
await L9Rum.shutdown(); // flush + full teardown; a later initialize() re-arms RUM
}
  • shutdown() flushes pending spans and fully tears RUM down so a later initialize() starts a clean flow.
  • isActive() reports whether RUM is currently running.

WebView correlation

From 1.11.1, L9Rum.instrumentWebView(controller) gives a webview_flutter WebView to the native instrument(webView) API, as L9Rum.instrumentWebView does in React Native. Native then:

  • Injects the native session.id and native.view.id on each navigation, so Browser RUM spans from the page share the native session.
  • Names each WebView page view from the folded URL path, sets view.url, and sets view.type=webview, so the dashboard marks WebView views.

Pass a WebViewController, its platform controller (AndroidWebViewController / WebKitWebViewController), or the webViewIdentifier of the platform controller. The plugin does not add a webview_flutter dependency. It finds the native WebView through the public external API of webview_flutter_android and webview_flutter_wkwebview.

import 'package:flutter/material.dart';
import 'package:webview_flutter/webview_flutter.dart';
import 'package:last9_rum_flutter/last9_rum_flutter.dart';
class ProductPage extends StatefulWidget {
const ProductPage({super.key});
@override
State<ProductPage> createState() => _ProductPageState();
}
class _ProductPageState extends State<ProductPage> {
final WebViewController _controller = WebViewController();
@override
void initState() {
super.initState();
_load();
}
Future<void> _load() async {
await L9Rum.startView('ProductPage');
await _controller.setJavaScriptMode(JavaScriptMode.unrestricted);
await _controller.setNavigationDelegate(NavigationDelegate());
// After startView and setNavigationDelegate, before loadRequest.
await L9Rum.instrumentWebView(_controller);
await _controller.loadRequest(Uri.parse('https://app.example.com/product/42'));
}
@override
Widget build(BuildContext context) =>
Scaffold(body: WebViewWidget(controller: _controller));
}

Call instrumentWebView in this order:

  1. After L9Rum.startView(...) for the host screen. Native binds the WebView to the view that is active at that time.
  2. After setNavigationDelegate. Native wraps the navigation delegate that is set when it installs (Android WebViewClient, iOS WKNavigationDelegate) and forwards each callback to it. A delegate that you set later replaces the Last9 wrapper.
  3. Before loadRequest.

instrumentWebView returns false and does not instrument the WebView when:

  • The plugin cannot find the native WebView, for example for a WebView plugin other than webview_flutter.
  • The device runs Android below API 26 (8.0). Native can read the current WebViewClient only from API 26. Below API 26, native would replace the webview_flutter client and drop the onNavigationRequest and page callbacks of the app, so the plugin keeps the client of the app.

The Android plugin includes consumer ProGuard rules that keep WebViewFlutterAndroidExternalApi in minified apps. You do not need to add rules.

To auto-load Last9 Browser RUM into an instrumented WebView, set webViewAutoLoadBrowserRum: true in L9RumConfig. The WebView then loads Browser RUM from the CDN and initializes it with the baseUrl and clientToken of the app. Enable it only for WebViews that load content that you trust, because any main-frame script can read the clientToken.

Script fallback for other WebViews

For WebViews where instrumentWebView returns false, and on plugin 1.11.0 and earlier, use L9Rum.getWebViewInjectedJavaScript(). It returns a script that writes the current native session.id and native.view.id into the WebView so Browser RUM spans share the native session. Pair it with webview_flutter’s NavigationDelegate.onPageStarted so id rollovers reach the page on every navigation:

import 'package:webview_flutter/webview_flutter.dart';
import 'package:last9_rum_flutter/last9_rum_flutter.dart';
Future<void> setupProductWebView() async {
late final WebViewController controller;
controller = WebViewController()
..setJavaScriptMode(JavaScriptMode.unrestricted)
..setNavigationDelegate(NavigationDelegate(
onPageStarted: (_) async {
final script = await L9Rum.getWebViewInjectedJavaScript();
await controller.runJavaScript(script);
},
))
..loadRequest(Uri.parse('https://app.example.com'));
}

Calling getWebViewInjectedJavaScript() also stamps the active native view with view.type=webview. Call it after L9Rum.startView(...) so the marker lands on the right view.

In-WebView SPA routes stay on Browser RUM startView(). See the WebView Session Correlation guide for the full pattern, auto-load options, and verification steps.

Next steps

Once data is flowing, explore it in Discover > Applications — performance, errors, and sessions.

For the version history of this SDK, see the RUM changelog.


Troubleshooting

  • No data showing? Verify your baseUrl, clientToken, and origin. Each platform needs its own Client token and origin pair (android://<package> on Android, ios://<bundle-id> on iOS). Run await L9Rum.sendTestEvent() and read status and error (see Check the connection from code).
  • sendTestEvent returns not_supported? The native part of the plugin does not have the method. Make sure that the Dart package and the native plugin come from the same tarball (1.14.0 or later), then rebuild the app.
  • sendTestEvent returns session_not_sampled? The session is not sampled. Set sampleRate: 100 while you verify the setup.
  • A feature from this page is missing? stable/v1 serves 1.8.0. Features from 1.9.0 and later need a versioned tarball (see CDN artifacts).
  • instrumentWebView returns false? Make sure that you use webview_flutter and that the device runs Android API 26 or later. For other WebViews, use getWebViewInjectedJavaScript().
  • Warning that names graphqlDetail? You set a deprecated option (captureVariables, variableAllowList, or captureErrorMessages) on L9GqlLink or L9DioInterceptor. These options have no effect from 1.12.0. Use graphqlDetail.
  • NATIVE_HTTP_RESPONSE_TOO_LARGE error? A response through L9Rum.instrumentedHttpClient() is larger than 10 MB. Use the default dart:io client for that request.

Please get in touch with us on Discord or Email if you have any questions.