Copy as Markdown[Open in ChatGPT](https://chatgpt.com/?q=Read%20https%3A%2F%2Fdocs-docusaurus.kinsta.page%2Fuser-guides%2Frum%2Fsdk-installation%2Fflutter%2Fmobile.md%20and%20help%20me%20with%20my%20question%20about%20this%20Coralogix%20documentation%20page.)[Open in Claude](https://claude.ai/new?q=Read%20https%3A%2F%2Fdocs-docusaurus.kinsta.page%2Fuser-guides%2Frum%2Fsdk-installation%2Fflutter%2Fmobile.md%20and%20help%20me%20with%20my%20question%20about%20this%20Coralogix%20documentation%20page.)

# Mobile 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)](https://docs-docusaurus.kinsta.page/user-guides/rum/getting-started/real-user-monitoring/.md).

## Overview[​](#overview "Direct link to 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.

## Prerequisites[​](#prerequisites "Direct link to Prerequisites")

* Flutter SDK version ver 3.3.0 or above.
* Dart SDK version 3.4.1 - 4.0.0.

## Installation[​](#installation "Direct link to Installation")

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

```
flutter pub add cx_flutter_plugin
```

## Configure[​](#configure "Direct link to Configure")

To initialize the RUM SDK, input both `CXExporterOptions` and `CXDomain`.

```
Future<void> initPlatformState() async {

  // Setup the cx SDK

  var userContext = UserMetadata(

    userId: '123',

    userName: 'John Doe',

    userEmail: 'john.doe@example.com',

    userMetadata: {'item1': '1999'},

  );

  var coralogixDomain = CXDomain.eu2;

  var options = CXExporterOptions(

    coralogixDomain: coralogixDomain,

    userContext: userContext,

    environment: 'production',

    application: 'App name',

    version: '1.0.0',

    publicKey: 'Your public key',

    ignoreUrls: [],

    ignoreErrors: [],

    proxyUrl: 'https://your.proxy.url',

    labels: {'item': 'playstation 5', 'itemPrice': 1999},

    sdkSampler: 100,

    mobileVitalsFPSSamplingRate: 300,

    instrumentations: { CXInstrumentationType.anr.value: true,

                        CXInstrumentationType.custom.value: true,

                        CXInstrumentationType.errors.value: true,

                        CXInstrumentationType.lifeCycle.value: true,

                        CXInstrumentationType.mobileVitals.value: true,

                        CXInstrumentationType.navigation.value: true,

                        CXInstrumentationType.network.value: true,

                        CXInstrumentationType.userActions.value: true},

    collectIPData: true,

    debug: true,

  );

  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;

}
```

| Field                  | Description                                                                                                                                                                   | Example                                                                                                                                       |
| ---------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------- |
| `coralogixDomain`      | The region associated with your Coralogix [**domain**](https://docs-docusaurus.kinsta.page/user-guides/account-management/account-settings/coralogix-domain/.md).             | `EU1, EU2, US1, US2, US3, AP1, AP2, AP3`                                                                                                      |
| `userContext`          | User context information, such as user ID, name, email, and additional metadata.                                                                                              | `var userContext = UserMetadata( userId: '123', userName: 'John Doe', userEmail: 'john.doe@example.com', userMetadata: {'item1': '1999'}, );` |
| `environment`          | The environment in which the application is running (e.g., production, staging).                                                                                              | `"production"`                                                                                                                                |
| `application`          | The name of the application.                                                                                                                                                  | `"MyApp"`                                                                                                                                     |
| `version`              | The version of the application.                                                                                                                                               | `"1.0.0"`                                                                                                                                     |
| `publicKey`            | Coralogix token, publicly-visible publicKey value. This is a required property.                                                                                               | `"my_public_key"`                                                                                                                             |
| `ignoreUrls`           | A list of URLs to ignore for logging and monitoring purposes.                                                                                                                 | `["https://example.com/api"]`                                                                                                                 |
| `ignoreErrors`         | A list of errors to ignore for logging and monitoring purposes.                                                                                                               | `["NotFoundError", "TimeoutError"]`                                                                                                           |
| `proxyUrl`             | A proxy URL for routing data when the default Coralogix domain is not reachable.                                                                                              | `"https://proxy.example.com"`                                                                                                                 |
| `labels`               | A set of key-value pairs for additional metadata or labels to attach to logs and monitoring data.                                                                             | `{ environment: "production", region: "us-east-1"}`                                                                                           |
| `debug`                | A boolean flag to enable or disable debug mode for additional logging and diagnostics.                                                                                        | `true` or `false`                                                                                                                             |
| `networkCaptureConfig` | Per-URL rules for capturing request and response headers and payloads. See [Network capture rules](#network-capture-rules).                                                   | `[CxNetworkCaptureRule(urlPattern: 'https://api.example.com/.*', collectReqPayload: true)]`                                                   |
| `beforeSend`           | Callback to inspect, modify, or discard each event before it reaches Coralogix. See [Modify events with beforeSend](#modify-events-with-beforesend).                          | `(event) => BeforeSendResult(event: event)`                                                                                                   |
| `enableSwizzling`      | (iOS-only effect) Enables `URLSession` method swizzling for network instrumentation. The native layer treats a missing flag as enabled. Pass `true` for full instrumentation. | `true`                                                                                                                                        |

## Network capture rules[​](#network-capture-rules "Direct link to Network capture rules")

By default, the SDK captures request URLs, status codes, and timings via `CxHttpClient` and `CxDioInterceptor`. Use `networkCaptureConfig` in `CXExporterOptions` to capture specific request and response headers or payloads on a per-URL basis.

```
var options = CXExporterOptions(

  // ...

  networkCaptureConfig: [

    CxNetworkCaptureRule(

      urlPattern: 'https://api.example.com/.*',

      reqHeaders: ['X-Request-Id'],

      resHeaders: ['X-Response-Time'],

      collectReqPayload: true,

      collectResPayload: false,

    ),

  ],

);
```

| `CxNetworkCaptureRule` field | Description                                                  |
| ---------------------------- | ------------------------------------------------------------ |
| `urlPattern`                 | Regex pattern that matches request URLs the rule applies to. |
| `reqHeaders`                 | List of request header names to capture.                     |
| `resHeaders`                 | List of response header names to capture.                    |
| `collectReqPayload`          | When `true`, capture the request body.                       |
| `collectResPayload`          | When `true`, capture the response body.                      |

## Modify events with beforeSend[​](#modify-events-with-beforesend "Direct link to Modify events with beforeSend")

Use `beforeSend` to inspect, transform, or discard events before they reach Coralogix. Return a `BeforeSendResult` with `event: null` to drop the event.

```
var options = CXExporterOptions(

  // ...

  beforeSend: (event) {

    if (event.userContext?.userEmail?.endsWith('@coralogix.com') ?? false) {

      return BeforeSendResult(event: null);

    }

    return BeforeSendResult(event: event);

  },

);
```

## Instrumentation[​](#instrumentation "Direct link to 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.

* **errors** - Monitors error events.
* **network** - Intercepts and reports network calls.
* **custom** - Allows developers to define and track custom events, giving insights into specific actions or behaviors in the application that are critical to the business.
* **anr** - Automatically detects Application Not Responsive (ANR) events.
* **mobileVitals** - Automatically tracks cold/warm start times and Frame Rate (FPS).
* **lifeCycle** - Captures the application lifecycle events as they are defined in each platform (Android/iOS).
* **navigation** - Identifies user movement between app screens.
* **userActions** – Catches user actions, such as button taps, tab activations, and other navigation controllers. It creates a span with a severity level of `info` and an event type of `user-interaction`, incorporating details about the element, including the text displayed on it.

## Integration functions[​](#integration-functions "Direct link to Integration functions")

This section lists public functions used to interact with the Coralogix RUM SDK.

### Monitor network requests[​](#monitor-network-requests "Direct link to Monitor network requests")

Use `CxHttpClient` to monitor the HTTP traffic.

```
final client = CxHttpClient();

await client.get(Uri.parse(url));
```

### Report unhandled/handled exceptions[​](#report-unhandledhandled-exceptions "Direct link to Report 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}, "");
```

### Report unhandled exceptions[​](#report-unhandled-exceptions "Direct link to Report 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());

  });

}
```

### Customize logs[​](#customize-logs "Direct link to Customize logs")

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

### Monitor page views[​](#monitor-page-views "Direct link to Monitor page views")

```
await CxFlutterPlugin.setView(viewName);
```

### Set labels[​](#set-labels "Direct link to Set labels")

Set the labels for the Coralogix exporter.

```
final labels = {'stock': 'NVDA', 'price': 104};

await CxFlutterPlugin.setLabels(labels);
```

### Set user context[​](#set-user-context "Direct link to Set user context")

```
var userContext = UserMetadata(

  userId: '456',

  userName: 'Robert Davis',

  userEmail: 'robert.davis@example.com',

  userMetadata: {'car': 'tesla'},

);



await CxFlutterPlugin.setUserContext(userContext);
```

### Utility methods[​](#utility-methods "Direct link to Utility methods")

Inspect SDK state or update context at runtime.

```
// Confirm the SDK is initialized.

final initialized = await CxFlutterPlugin.isInitialized();



// Read the current session ID.

final sessionId = await CxFlutterPlugin.getSessionId();



// Read the current labels.

final labels = await CxFlutterPlugin.getLabels();



// Update the application context after init.

await CxFlutterPlugin.setApplicationContext('my-app', '1.2.0');
```

### Shut down the exporter[​](#shut-down-the-exporter "Direct link to Shut down the exporter")

Shut down the Coralogix exporter and mark it as uninitialized.

```
await CxFlutterPlugin.shutdown();
```

For more information, check the [Coralogix iOS SDK repository](https://github.com/coralogix/cx-ios-sdk).

## Additional resources[​](#additional-resources "Direct link to Additional resources")

|                        |                                                               |
| ---------------------- | ------------------------------------------------------------- |
| External documentation | [pub.dev package](https://pub.dev/packages/cx_flutter_plugin) |
