# Build with Flutter & Dart

Start collecting session telemetry, connect Flutter navigation once, then add logs, handled errors, and custom events.

Source: https://appportal.io/docs/sdks/flutter

Start one client before `runApp` to create a session with app, platform, and version context.
Connect navigation at the app level, then add logs, errors, and outcomes from your own code.
AppPortal sends the collected telemetry in the background.

## Install the package

Use Flutter **3.38.1+** and Dart **3.10+**, below 4.0. Request Flutter SDK preview access from
AppPortal to get the repository URL, access, and an approved commit SHA. Authenticate Git locally and in CI,
then add the dependency to `pubspec.yaml`:

```yaml
dependencies:
  appportal:
    git:
      url: <preview-repository-url>
      ref: <approved-preview-commit-sha>
```

Use the repository URL and full commit SHA you received, then run `flutter pub get`.
Commit `pubspec.yaml` and `pubspec.lock` so your app and CI use the same revision.

## Start in main

Add startup to your existing entry point. `MyApp` below is your application's root widget:

```dart
import 'package:appportal/telemetry.dart';
import 'package:flutter/widgets.dart';

void main() {
  AppPortal.createBuilder('<app-credential>').start();
  runApp(const MyApp());
}
```

The builder initializes Flutter bindings and returns an `AppPortalClient`. If you use Provider,
Riverpod, or GetIt, register that returned instance for injection. `AppPortal` delegates to the
same client, so shared services and widget code do not need separate runtimes.

The credential selects the app and environment on the server. The SDK supplies the canonical
AppPortal endpoint; your app does not configure a host or supply separate account or environment values.

## Connect your consent UI

Collection starts **pending**: records stay in a bounded local quarantine. Connect these methods
to separate actions in your existing privacy settings:

```dart
void allowTelemetry() => AppPortal.grantConsent();
void declineTelemetry() => AppPortal.revokeConsent();
```

The SDK restores the saved decision for this credential before sending telemetry. Revoking consent
erases unsent records and stops capture. `resetConsent()` returns to pending. A saved decision
wins over `.withInitialConsent(...)`; avoid granting on every launch. Preference writes are
asynchronous, so abrupt termination can interrupt saving the latest choice.

## See your first session

The client creates a session when it starts; no custom event is needed to create it.
After opting in, keep the app online and [find the run in Sessions](https://appportal.io/docs/getting-started/first-event#5-find-your-session).
The SDK attaches the same session ID to subsequent screens, logs, errors, and events, and owns
batching and retries. Your app does not need to flush or close it.

Flutter does not observe app foreground/background transitions or measure startup and HTTP
requests automatically. Connect the navigation observer below and add explicit timings for work
you need to measure. Do not expect native lifecycle entries from installing this package alone.

## Connect navigation once

Attach an app-owned [Navigator observer](https://api.flutter.dev/flutter/widgets/Navigator/observers.html)
at your navigation host. This observes screen changes globally, including push and pop, through
[`didChangeTop`](https://api.flutter.dev/flutter/widgets/NavigatorObserver/didChangeTop.html):

```dart
import 'package:appportal/telemetry.dart';
import 'package:flutter/widgets.dart';

class TelemetryNavigatorObserver extends NavigatorObserver {
  static const screenNames = {
    '/': 'home',
    '/catalog': 'catalog',
    '/checkout': 'checkout',
  };

  @override
  void didChangeTop(Route<dynamic> topRoute, Route<dynamic>? previousTopRoute) {
    final screen = screenNames[topRoute.settings.name];
    if (screen != null) AppPortal.trackScreen(screen);
  }
}
```

Retain an instance in your app's State:

```dart
final _navigationTelemetry = TelemetryNavigatorObserver();
```

Add it to your existing `MaterialApp` or `CupertinoApp` configuration:

```dart
navigatorObservers: [_navigationTelemetry],
```

Replace the map with your app's stable route names. For a Router-based app, pass the observer to
the router's navigator configuration, or call `trackScreen` in its central route-change callback.
Use a separate observer for each Navigator you track. Do not also report the same screen from
every widget, or put route arguments and IDs in screen names. This records screen context;
it does not measure how long deferred content takes to load.

## Add logs and report handled errors

Log operational detail and report caught errors with their stack traces at the recovery boundary.
Here `catalog` is your application's existing catalog service:

```dart
import 'package:appportal/telemetry.dart';

AppPortal.info('Catalog refresh started');
try {
  await catalog.refresh();
} catch (error, stackTrace) {
  AppPortal.captureError(
    error,
    stackTrace: stackTrace,
    properties: {'operation': 'catalog.refresh'},
  );
  AppPortal.warn('Catalog refresh failed; keeping cached data');
  // Keep the app's normal recovery or error display here.
}
```

`debug`, `info`, `warn`, and `error` produce diagnostic logs. `captureError` includes the caught
error and stack trace. An error-severity log alone does not capture an exception. Report a handled
failure once, at the layer that has enough context to recover.

## Add custom events

After your checkout API confirms an order, record a stable event and a bounded dimension:

```dart
AppPortal.trackEvent(
  'checkout.completed',
  properties: {'fulfillment': 'pickup'},
);
```

Avoid names, order details, and free-form input. If you need signed-in user context,
call `AppPortal.identify(userId)` with an opaque identifier and `AppPortal.clearUser()` on sign-out.
User traits are not included in Flutter's telemetry payloads.

## Follow the session timeline

Run a flow with consent granted: visit a named screen, refresh the catalog, and exercise a
recoverable failure. Open **Sessions** in the Dashboard and choose the run's **Session story**.
Screens, logs, errors, and custom events share `AppPortal.sessionId` automatically.

Use **Logs** to search diagnostic messages and **Crashes** to inspect the handled error and stack
trace. [Investigate an app session](https://appportal.io/docs/guides/investigate-session) explains how to follow these
signals through the timeline. Manual `startSpan` and `trackMetric` APIs add performance measurements.

## Add Messaging or Location

Import the capabilities your app uses and bind them to the same client:

```dart
import 'package:appportal/messaging.dart';
import 'package:appportal/location.dart';

final messaging = AppPortalMessaging.forClient(AppPortal.current);
final location = AppPortalLocation.forClient(AppPortal.current);
```

These are separate libraries in the `appportal` package. Operational requests use their own
permissions and remain available while telemetry consent is pending or denied. Queued push and
location telemetry still follows the telemetry consent decision. See the
[Messaging prerequisites](https://appportal.io/docs/sdks/messaging) and [Location guide](https://appportal.io/docs/sdks/location).
Neither module requests OS permissions or registers native geofences automatically.

If your app supplies an `http.Client` through `.withHttpClient(client)`, that same client handles
telemetry and both capabilities. It remains owned by your application.

## Know the current limits

The current Flutter SDK source uses a **bounded platform-preferences queue** that restores before
sending. Writes are asynchronous: abrupt termination before a write completes can lose the latest
captures. A compatible published package version for this behavior has not been verified; check your
installed version before relying on persistence.

The SDK does not provide a persistent installation ID, synchronous native fatal-crash/ANR capture,
automatic host instrumentation, or crash breadcrumb serialization.
The [.NET geofence planner](https://appportal.io/docs/sdks/dotnet/geofencing) is unavailable in Flutter.

Existing `init`, `flush`, `close`, and the `appportal.dart` umbrella remain compatibility APIs.
Legacy scope arguments are ignored; use the credential-only builder for new code.
See [SDK compatibility](https://appportal.io/docs/sdks/compatibility) when choosing a host.
