Installation

Step-by-step setup for a new Flutter app — the git dependency, Android Gradle and iOS CocoaPods or SwiftPM wiring, native start calls, and the Dart start sequence.

Setup has three parts: the Dart package, the native SDK on each platform, and a start call in each place. The native part is required. The collector address and service key are native configuration, and on iOS the Flutter plugin cannot start the SDK by itself. This page goes through an app made with flutter create from start to finish.

Quick start

Enter the collector URL, project, app and app key below and pick a tab (Android · iOS) to generate the native config file from those values. The Flutter SDK's Dart start call takes no identity arguments, so the collector address and app key go into this native file, not into Dart code. Advanced options are behind the "Advanced options" toggle.

android/app/src/main/sophonz-config.json
{
  "sdk_config": {
    "app_framework": "flutter",
    "ingest": {
      "collector_url": "https://in.sophonz.ai",
      "service_key": "sk_tYtJUa4WweXXedj6lxjSqoPW5O0DnbXz",
      "service_namespace": "sophonz"
    }
  }
}

Requirements

ItemRequirement
Flutter3.22 or higher
Dart3.4 or higher. Earlier versions do not resolve the relative path: dependencies inside a git dependency
AndroidSophonz Gradle plugin 1.0.0 applied to the app module; minSdk 21 or higher (below 26 needs core library desugaring)
iOS13.0 or higher; Sophonz Apple SDK (SophonzIO) 1.0.0
AccessRead access to sophonz-labs/sophonz-flutter-sdk and sophonz-labs/sophonz-apple-sdk, and a GitHub token with read:packages for the Android artifacts

Release v0.1.0 of the Flutter SDK is built against Sophonz Android SDK 1.0.0 and SophonzIO 1.0.0. The native versions below have to match those.

1. Add the Dart package

The packages are not on pub.dev. Each release is a git tag of the SDK repository with a GitHub Release, and the app depends on the tag.

pubspec.yaml
dependencies:
  flutter:
    sdk: flutter
  sophonz:
    git:
      url: git@github.com:sophonz-labs/sophonz-flutter-sdk.git
      path: sophonz
      ref: v0.1.0
flutter pub get

sophonz pulls in sophonz_android, sophonz_ios and sophonz_platform_interface from the same tag. The packages refer to each other by relative path, and pub resolves those paths inside the same checkout. pubspec.lock records the commit the tag resolved to.

Repository access

The repository is private. Everyone who runs flutter pub get needs read access, developers and CI alike.

  • SSH — the URL above uses your SSH key. Check with ssh -T git@github.com.
  • HTTPS — write https://github.com/sophonz-labs/sophonz-flutter-sdk.git instead and set up a git credential helper, for example gh auth setup-git.

In CI, rewrite GitHub URLs to use a token before flutter pub get. This covers both the SSH URL in pubspec.yaml and the HTTPS URLs CocoaPods uses later.

.github/workflows/build.yml
- name: Git access to private SDK repositories
  env:
    GH_TOKEN: ${{ secrets.SOPHONZ_SDK_READ_TOKEN }}
  run: |
    git config --global url."https://x-access-token:${GH_TOKEN}@github.com/".insteadOf "git@github.com:"
    git config --global url."https://x-access-token:${GH_TOKEN}@github.com/".insteadOf "https://github.com/" --add
- run: flutter pub get

The token needs read access to sophonz-flutter-sdk and sophonz-apple-sdk.

Adding sophonz_dio or sophonz_go_router

Add them with their own path and the same url and ref. Then repeat the sophonz entry under dependency_overrides.

pubspec.yaml
dependencies:
  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
 
dependency_overrides:
  sophonz:
    git:
      url: git@github.com:sophonz-labs/sophonz-flutter-sdk.git
      path: sophonz
      ref: v0.1.0

NOTE — Why the override is needed

sophonz_dio depends on sophonz through a relative path inside its checkout. Pub pins that dependency to the commit the tag resolved to, not to the name v0.1.0. Your own sophonz entry names the tag, so pub sees two different git descriptions of one package and stops with sophonz_dio from git is forbidden. The override tells pub to use one description for both.

If you import sophonz_platform_interface directly (for ErrorCode or LastRunEndState, see the API reference), list it the same way under both dependencies and dependency_overrides, with path: sophonz_platform_interface.

2. Android

Token for GitHub Packages

The Sophonz Android SDK and its Gradle plugin come from GitHub Packages, which requires a token even to read. Use a classic personal access token with read:packages. Fine-grained tokens do not work with GitHub Packages.

~/.gradle/gradle.properties
gpr.user=your-github-username
gpr.key=ghp_...

Keep the token out of the project's android/gradle.properties, which is committed. In CI, write the two lines to ~/.gradle/gradle.properties in a step before the build.

CAUTION — 403 and 404 look the same

When the token is missing or lacks read:packages, Gradle reports "Could not resolve io.sophonz:…", the same message as for a version that does not exist. Check the token before changing the version.

Repositories and the Gradle plugin

Recent Flutter versions create the Android project with the Kotlin DSL (settings.gradle.kts, build.gradle.kts, app/build.gradle.kts). Projects created with older versions use Groovy (.gradle). Follow the tab that matches your files.

The repository has to be added in two places. Plugins resolve from pluginManagement. The sophonz_android plugin module resolves the SDK from the project repositories under allprojects.

android/settings.gradle.kts
pluginManagement {
    // ...flutterSdkPath and includeBuild generated by flutter create...
    repositories {
        google()
        mavenCentral()
        gradlePluginPortal()
        maven {
            url = uri("https://maven.pkg.github.com/sophonz-labs/sophonz-android-sdk")
            credentials {
                username = providers.gradleProperty("gpr.user").orNull
                password = providers.gradleProperty("gpr.key").orNull
            }
        }
    }
}
 
plugins {
    id("dev.flutter.flutter-plugin-loader") version "1.0.0"
    // ...com.android.application and kotlin plugins generated by flutter create...
    id("io.sophonz.gradle") version "1.0.0" apply false
}
android/build.gradle.kts
allprojects {
    repositories {
        google()
        mavenCentral()
        maven {
            url = uri("https://maven.pkg.github.com/sophonz-labs/sophonz-android-sdk")
            credentials {
                username = providers.gradleProperty("gpr.user").orNull
                password = providers.gradleProperty("gpr.key").orNull
            }
        }
    }
}
android/app/build.gradle.kts
plugins {
    // ...com.android.application, Kotlin and dev.flutter.flutter-gradle-plugin generated by flutter create...
    id("io.sophonz.gradle")
}

The Gradle plugin reads sophonz-config.json at build time, builds it into the SDK, and adds the SDK to the app. The Flutter plugin compiles against the SDK but does not bundle it, so without the Gradle plugin the app has no SDK at runtime.

CAUTION — Keep the Gradle plugin at the Flutter plugin's SDK version

The Gradle plugin adds the SDK at its own version. For v0.1.0 that is 1.0.0. With a different version, a call from Dart can reach a method the runtime SDK does not have.

minSdk below 26

flutter.minSdkVersion in the generated app/build.gradle.kts may be below 26. In that case the Android SDK needs core library desugaring, Android Gradle Plugin 8.3.0 or higher, and a gradle.properties flag. The Gradle plugin checks this at configuration time and names what is missing.

android/app/build.gradle.kts
android {
    compileOptions {
        isCoreLibraryDesugaringEnabled = true
    }
}
 
dependencies {
    coreLibraryDesugaring("com.android.tools:desugar_jdk_libs:2.1.4")
}
android/gradle.properties
android.useFullClasspathForDexingTransform=true

Setting minSdk = 26 in defaultConfig avoids all three. The full Android requirements are in the Android installation guide.

sophonz-config.json

Create the file in the app module. The Gradle plugin reads it during the build, so a change needs a rebuild.

android/app/src/main/sophonz-config.json
{
  "sdk_config": {
    "app_framework": "flutter",
    "ingest": {
      "collector_url": "https://in.sophonz.ai",
      "service_key": "sk_replace_me",
      "service_namespace": "my-project",
      "deployment_environment": "production"
    }
  }
}

app_framework: flutter marks the app as a Flutter app. Every key is described in Configuration.

Start the SDK in Application.onCreate

The template has no Application subclass, so add one. Use the package from namespace in app/build.gradle.kts.

android/app/src/main/kotlin/com/example/my_app/MainApplication.kt
package com.example.my_app
 
import android.app.Application
import io.sophonz.android.sophonzsdk.Sophonz
 
class MainApplication : Application() {
    override fun onCreate() {
        super.onCreate()
        Sophonz.start(this)
    }
}

Register it in the manifest, replacing the generated android:name="${applicationName}":

android/app/src/main/AndroidManifest.xml
<application
    android:name=".MainApplication"
    android:label="my_app"
    android:icon="@mipmap/ic_launcher">

If you skip this step, the Flutter plugin starts the SDK when Dart calls Sophonz.instance.start(). Everything still works, but the start happens after the Flutter engine is up, so app startup is not measured.

3. iOS

Add the Apple SDK

Flutter uses CocoaPods by default. sophonz_ios depends on the SophonzIO pod, which is not on CocoaPods trunk, so name its git source in the Runner target.

ios/Podfile
platform :ios, '13.0'
 
target 'Runner' do
  pod 'SophonzIO', :git => 'https://github.com/sophonz-labs/sophonz-apple-sdk.git', :tag => 'v1.0.0'
  use_frameworks!
  flutter_install_all_ios_pods File.dirname(File.realpath(__FILE__))
end

Keep the rest of the generated Podfile as it is. Then:

cd ios && pod install

sophonz-apple-sdk is private too. CocoaPods and Xcode need GitHub credentials for it: HTTPS credentials in the keychain, or an SSH key with the Podfile source written as git@github.com:sophonz-labs/sophonz-apple-sdk.git. The CI URL rewrite above covers both.

Sophonz-Info.plist

Create ios/Sophonz-Info.plist and add it to the Runner target in Xcode (File > Add Files to "Runner", Runner target checked). The file must be in the app bundle. A file that only exists in the folder is not read.

ios/Sophonz-Info.plist
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
  <key>CollectorURL</key>
  <string>https://in.sophonz.ai</string>
  <key>AppKey</key>
  <string>sk_replace_me</string>
  <key>Project</key>
  <string>my-project</string>
  <key>DeploymentEnvironment</key>
  <string>production</string>
</dict>
</plist>

Put literal values here. Xcode does not expand $(...) build settings in a plist copied as a resource, and the SDK treats an unexpanded value as missing. Every key is listed in Configuration.

Start the SDK in the AppDelegate

The Apple SDK has to be started from native code, on the main thread, before the Flutter engine runs. The Flutter plugin only attaches to an SDK that is already running. If nothing starts it, every Dart call on iOS is silently ignored.

Add an init() to the generated AppDelegate. Leave the rest of the class as generated: newer templates register plugins in didInitializeImplicitFlutterEngine, older ones in application(_:didFinishLaunchingWithOptions:).

ios/Runner/AppDelegate.swift
import Flutter
import UIKit
import SophonzIO
 
@main
@objc class AppDelegate: FlutterAppDelegate {
  override init() {
    super.init()
    // Reads Sophonz-Info.plist. nil when CollectorURL or AppKey is missing, empty or an unexpanded $(...).
    guard let options = Sophonz.Options.fromPlist(platform: .flutter) else {
      print("[sophonz] Sophonz-Info.plist is not configured; SDK not started")
      return
    }
    do {
      try Sophonz.start(options: options)
    } catch {
      // A failed start must not block the launch.
      print("[sophonz] failed to start: \(error)")
    }
  }
 
  // ...plugin registration generated by flutter create...
}

Starting in init() rather than in didFinishLaunching lets the SDK observe app startup. platform: .flutter marks the app as a Flutter app. Push notification capture and other start options are covered in Configuration.

4. Start the SDK in Dart

Call start first in main and pass the app as action, so uncaught errors are captured.

lib/main.dart
import 'package:flutter/material.dart';
import 'package:sophonz/sophonz.dart';
 
Future<void> main() async {
  await Sophonz.instance.start(action: () => runApp(const MyApp()));
}

start does the following, in order:

  1. Calls WidgetsFlutterBinding.ensureInitialized() and records the Dart start time.
  2. Forwards any exporters added with addSpanExporter or addLogRecordExporter (Android only).
  3. Attaches to the native SDK. On Android it starts the SDK if Application.onCreate() did not.
  4. Starts frame, UI isolate hang and lifecycle monitoring.
  5. With action, installs the error handlers, runs action, and records time to first frame.

Anything that must run before runApp, such as reading local settings, goes inside action:

Future<void> main() async {
  await Sophonz.instance.start(action: () async {
    final settings = await AppSettings.load();
    runApp(MyApp(settings: settings));
  });
}

A call made on Sophonz.instance before start has attached is dropped, not queued.

Routes and HTTP

Add a navigation observer so routes become views and screen-load spans:

MaterialApp(
  navigatorObservers: [SophonzNavigationObserver()],
  home: const HomePage(),
);

For HTTP, use SophonzHttpClient in place of http.Client, or add SophonzInterceptor() from sophonz_dio to a Dio instance:

final client = SophonzHttpClient();
final response = await client.get(Uri.parse('https://api.example.com/items'));

Both are covered in detail in Navigation and Networking.

5. Verify

  1. Run in debug mode and look for Sophonz Flutter SDK attached to host SDK successfully. in the console.
  2. If you see The Sophonz SDK was not started in native code instead, the native start is missing. On Android the plugin starts the SDK anyway, without startup timing. On iOS nothing is recorded until Sophonz.start(options:) is in the AppDelegate.
  3. On iOS, send the app to the background. The Apple SDK uploads when a session part ends, not on a timer, so a foregrounded app has not sent anything yet.
  4. Find the session in Sophonz. If nothing arrives, check the service key first. The collector drops telemetry with a missing or unregistered key without reporting an error.

Next

  • Configuration — native keys, start options and Dart options
  • Instrumentation — what is captured without any code
  • Examples — a complete main.dart with Dio, go_router, spans and errors

TIP — This is just the beginning

Now ship your app. Sophonz surfaces the problems real users hit — so your app evolves on its own.