Skip to content

Flutter

The Coralogix RUM Mobile SDK is a library (plugin) for Flutter that provides mobile telemetry instrumentation. Learn how to integrate with Coralogix's Real User Monitoring (RUM).

Overview

The Coralogix RUM Mobile SDK is a library (plugin) for Flutter that provides mobile telemetry instrumentation. The SDK captures:

  • HTTP requests

  • Unhandled/handled exceptions

  • Custom logs

  • Crashes (iOS Native using PLCrashReporter)

  • Views

Coralogix captures data using an SDK within your application's runtime. These platform-specific SDKs allow Coralogix to gain a deep understanding of how your application works, enabling comprehensive real-user monitoring and performance analysis.

Installation

To add the Coralogix dependency, navigate to the root folder of your Flutter app and run:

flutter pub add cx_flutter_plugin

Configure

To initialize the RUM SDK, you need to input both CXExporterOptions and CXDomain.

import 'package:cx_flutter_plugin/cx_http_client.dart';

class _MyAppState extends State<MyApp> {
  @override
  void initState() {
    super.initState();
    initPlatformState();
  }

  Future<void> initPlatformState() async {
    var coralogixDomain = <span class="domain-value"></span>;

    var options = CXExporterOptions(
      coralogixDomain: <span class="domain-value"></span>,
      userContext: null,
      environment: '<Environment>',
      application: '<App Name>',
      version: '<App Version>',
      publicKey: '<PublicKey>',
      ignoreUrls: [],
      ignoreErrors: [],
      customDomainUrl: '',
      labels: {'item': 'playstation 5', 'itemPrice': 1999},
      debug: false,
    );

    await CxFlutterPlugin.initSdk(options);

    // If the widget was removed from the tree while the asynchronous platform
    // message was in flight, we want to discard the reply rather than calling
    // setState to update our non-existent appearance.
    if (!mounted) return;
  }
}
FieldDescriptionExample
coralogixDomainThe region associated with your Coralogix domain.US1, US2, EU1, EU2, 2PI, API
userContextUser context information, such as user ID, name, email, and additional metadata.var userContext = UserContext( userId: '123', userName: 'John Doe', userEmail: '[email protected]', userMetadata: {'item1': '1999'}, );
environmentThe environment in which the application is running (e.g., production, staging)."production"
applicationThe name of the application."MyApp"
versionThe version of the application."1.0.0"
publicKeyCoralogix token, publicly-visible publicKey value. This is a required property."my_public_key"
ignoreUrlsA list of URLs to ignore for logging and monitoring purposes.["https://example.com/api"]
ignoreErrorsA list of errors to ignore for logging and monitoring purposes.["NotFoundError", "TimeoutError"]
customDomainUrlA custom domain URL for sending data, if different from the default Coralogix domain."https://custom-domain.example.com"
labelsA set of key-value pairs for additional metadata or labels to attach to logs and monitoring data.{ environment: "production", region: "us-east-1"}
debugA boolean flag to enable or disable debug mode for additional logging and diagnostics.true or false

Network requests

By using CxHttpClient, the RUM SDK can monitor the HTTP traffic.

final client = CxHttpClient(http.Client());
await client.get(Uri.parse(url));

Unhandled/Handled exceptions

For handled exceptions, use a try/catch scheme with the reportError API.

try {
  throw StateError('state error try catch');
} catch (error, stackTrace) {
  if (error is StateError) {
    // Handle the StateError
    CxFlutterPlugin.reportError(error.message, {}, stackTrace.toString());
  }
}

Or

await CxFlutterPlugin.reportError('this is an error', {'fruit': 'banana', 'price': 1.30}, "");

Unhandled exceptions

Wrap your runApp function as follows:

void main() {
  runZonedGuarded(() {
    runApp(const MaterialApp(
      title: 'Navigation Basics',
      home: MyApp(),
    ));
  }, (error, stackTrace) {
    CxFlutterPlugin.reportError(error.toString(), {}, stackTrace.toString());
  });
}

Custom logs

await CxFlutterPlugin.log(CxLogSeverity.error, 'this is an error', {'fruit': 'banana', 'price': 1.30});

Views

To monitor page views, use the following API:

await CxFlutterPlugin.setView(viewName);

Set labels

Sets the labels for the Coralogix exporter.

final labels = {'stock': 'NVDA', 'price': 104};
await CxFlutterPlugin.setLabels(labels);

Set user context

Setting user context:

var userContext = UserContext(
  userId: '456',
  userName: 'Robert Davis',
  userEmail: '[email protected]',
  userMetadata: {'car': 'tesla'},
);

await CxFlutterPlugin.setUserContext(userContext);

Shutdown

Shuts down the Coralogix exporter and marks it as uninitialized.

await CxFlutterPlugin.shutdown();

For more information, check Coralogix SDK Documentation.

Instrumentation

Enable or disable specific instrumentation (see the list below), with the default set to all trues. Each instrumentation controls the data the SDK will track and collect.

  • xhr: true – Tracks XMLHttpRequest (XHR) network requests, capturing details about API calls and data exchanges happening in the background. This helps monitor the performance and success of server communication.

  • fetch: true – Monitors fetch requests, which are modern network requests used in web applications. It provides insights into how long these requests take and if they fail, improving the visibility of backend interactions.

  • web_vitals: true – Collects Web Vitals metrics, which are key performance indicators such as Largest Contentful Paint (LCP), First Input Delay (FID), and Cumulative Layout Shift (CLS), Interaction to Next Paint (INP), First Input Delay (FID), First Contentful Paint (FCP). These metrics help measure and optimize user experience.

  • interactions: true – Tracks user interactions like clicks, scrolling, and form inputs. This helps understand how users are engaging with the application and identifies responsiveness issues.

  • custom: true – Allows developers to define and track custom events, giving insights into specific actions or behaviors in the application that are critical to the business.

  • errors: true – Captures JavaScript errors, network errors, and other issues in the application. This data helps diagnose and resolve bugs or failures that affect the user experience.

  • long_tasks: true – Monitors long tasks that take more than 50ms to complete. Long tasks can make the application feel sluggish, so this helps in identifying performance bottlenecks.

  • resources: true – Collects data about resource loading performance, including images, scripts, and CSS files. This helps optimize resource usage and improve page load times by identifying slow-loading assets.

Example

CoralogixRum.init({
  // ...
  instrumentations: {
    xhr: true,
    fetch: true,
    web_vitals: false,
    interactions: false,
    custom: true,
    errors: true,
    long_tasks: true,
    resources: false,
  },
});

Additional resources

External documentationGitHub Repo

Support

Need help?

Our world-class customer success team is available 24/7 to walk you through your setup and answer any questions that may come up.

Feel free to reach out to us via our in-app chat or by sending us an email at [email protected].