Labsco
getsentry logo

sentry-flutter-sdk

โ˜… 233

by getsentry ยท part of getsentry/sentry-for-claude

Full Sentry SDK setup for Flutter and Dart. Use when asked to "add Sentry to Flutter", "install sentry_flutter", "setup Sentry in Dart", or configure error monitoring, tracing, profiling, session replay, or logging for Flutter applications. Supports Android, iOS, macOS, Linux, Windows, and Web.

๐Ÿ”Œ This skill ships inside the sentry plugin โ€” install the plugin and you also get 1 slash commands, an MCP server.

This is the playbook your agent receives when the skill activates โ€” you don't need to read it to use the skill, but it's here to audit before installing.

All Skills > SDK Setup > Flutter SDK

Sentry Flutter SDK

Opinionated wizard that scans your Flutter or Dart project and guides you through complete Sentry setup โ€” error monitoring, tracing, session replay, logging, profiling, and ecosystem integrations.

Invoke This Skill When

  • User asks to "add Sentry to Flutter" or "set up Sentry" in a Flutter or Dart app
  • User wants error monitoring, tracing, profiling, session replay, or logging in Flutter
  • User mentions sentry_flutter, sentry_dart, mobile error tracking, or Sentry for Flutter
  • User wants to monitor native crashes, ANRs, or app hangs on iOS/Android

Note: SDK versions and APIs below reflect sentry_flutter โ‰ฅ9.14.0 (current stable, February 2026). Always verify against docs.sentry.io/platforms/flutter/ before implementing.


Phase 1: Detect

Run these commands to understand the project before making any recommendations:

# Detect Flutter project type and existing Sentry
cat pubspec.yaml | grep -E '(sentry|flutter|dart)'

# Check SDK version
cat pubspec.yaml | grep -A2 'environment:'

# Check for existing Sentry initialization
grep -r "SentryFlutter.init\|Sentry.init" lib/ 2>/dev/null | head -5

# Detect navigation library
grep -E '(go_router|auto_route|get:|beamer|routemaster)' pubspec.yaml

# Detect HTTP client
grep -E '(dio:|http:|chopper:)' pubspec.yaml

# Detect database packages
grep -E '(sqflite|drift|hive|isar|floor)' pubspec.yaml

# Detect state management (for integration patterns)
grep -E '(flutter_bloc|riverpod|provider:|get:)' pubspec.yaml

# Detect GraphQL
grep -E '(graphql|ferry|gql)' pubspec.yaml

# Detect Firebase
grep -E '(firebase_core|supabase)' pubspec.yaml

# Detect backend for cross-link
ls ../backend/ ../server/ ../api/ 2>/dev/null
find .. -maxdepth 3 \( -name "go.mod" -o -name "requirements.txt" -o -name "Gemfile" -o -name "*.csproj" \) 2>/dev/null | grep -v flutter | head -10

# Detect platform targets
ls android/ ios/ macos/ linux/ windows/ web/ 2>/dev/null

What to determine:

QuestionImpact
sentry_flutter already in pubspec.yaml?Skip install, jump to feature config
Dart SDK >=3.5?Required for sentry_flutter โ‰ฅ9.0.0
go_router or auto_route present?Use SentryNavigatorObserver โ€” specific patterns apply
dio present?Recommend sentry_dio integration
sqflite, drift, hive, isar present?Recommend matching sentry_* DB package
Has android/ and ios/ directories?Full mobile feature set available
Has web/ directory only?Session Replay and Profiling unavailable
Has macos/ directory?Profiling available (alpha)
Backend directory detected?Trigger Phase 4 cross-link

Phase 2: Recommend

Present a concrete recommendation based on what you found. Don't ask open-ended questions โ€” lead with a proposal:

Recommended (core coverage โ€” always set up these):

  • โœ… Error Monitoring โ€” captures Dart exceptions, Flutter framework errors, and native crashes (iOS + Android)
  • โœ… Tracing โ€” auto-instruments navigation, app start, network requests, and UI interactions
  • โœ… Session Replay โ€” captures widget tree screenshots for debugging (iOS + Android only)

Optional (enhanced observability):

  • โšก Profiling โ€” CPU profiling; iOS and macOS only (alpha)
  • โšก Logging โ€” structured logs via Sentry.logger.* and sentry_logging integration
  • โšก Metrics โ€” counters, gauges, distributions (SDK โ‰ฅ9.11.0)

Platform limitations โ€” be upfront:

FeaturePlatformsNotes
Session ReplayiOS, AndroidNot available on macOS, Linux, Windows, Web
ProfilingiOS, macOSAlpha status; not available on Android, Linux, Windows, Web
Native crashesiOS, Android, macOSNDK/signal handling; Linux/Windows/Web: Dart exceptions only
App Start metricsiOS, AndroidNot available on desktop/web
Slow/frozen framesiOS, Android, macOSNot available on Linux, Windows, Web
CronsN/ANot available in the Flutter/Dart SDK

Propose: "For your Flutter app targeting iOS/Android, I recommend Error Monitoring + Tracing + Session Replay. Want me to also add Logging and Profiling (iOS/macOS alpha)?"


Phase 3: Guide

Determine Your Setup Path

Project typeRecommended setup
Any Flutter appWizard CLI (handles pubspec, init, symbol upload)
Manual preferredPath B below โ€” pubspec.yaml + main.dart
Dart-only (CLI, server)Path C below โ€” pure sentry package

You need to run this yourself โ€” the wizard opens a browser for login and requires interactive input that the agent can't handle. Copy-paste into your terminal:

brew install getsentry/tools/sentry-wizard && sentry-wizard -i flutter

It handles org/project selection, adds sentry_flutter to pubspec.yaml, updates main.dart, configures sentry_dart_plugin for debug symbol upload, and adds build scripts. Here's what it creates/modifies:

FileActionPurpose
pubspec.yamlAdds sentry_flutter dependency and sentry: config blockSDK + symbol upload config
lib/main.dartWraps main() with SentryFlutter.init()SDK initialization
android/app/build.gradleAdds Proguard config referenceAndroid obfuscation support
.sentryclircAuth token and org/project configSymbol upload credentials

Once it finishes, come back and skip to Verification.

If the user skips the wizard, proceed with Path B (Manual Setup) below.


Path B: Manual โ€” Flutter App

Step 1 โ€” Install

flutter pub add sentry_flutter

Or add to pubspec.yaml manually:

dependencies:
  flutter:
    sdk: flutter
  sentry_flutter: ^9.14.0

Then run:

flutter pub get

Step 2 โ€” Initialize Sentry in lib/main.dart

import 'package:flutter/widgets.dart';
import 'package:sentry_flutter/sentry_flutter.dart';

Future<void> main() async {
  await SentryFlutter.init(
    (options) {
      options.dsn = 'YOUR_SENTRY_DSN';
      options.sendDefaultPii = true;

      // Tracing
      options.tracesSampleRate = 1.0; // lower to 0.1โ€“0.2 in production

      // Profiling (iOS and macOS only โ€” alpha)
      options.profilesSampleRate = 1.0;

      // Session Replay (iOS and Android only)
      options.replay.sessionSampleRate = 0.1;
      options.replay.onErrorSampleRate = 1.0;

      // Structured Logging (SDK โ‰ฅ9.5.0)
      options.enableLogs = true;

      options.environment = const bool.fromEnvironment('dart.vm.product')
          ? 'production'
          : 'development';
    },
    // REQUIRED: wrap root widget to enable screenshots, replay, user interaction tracing
    appRunner: () => runApp(SentryWidget(child: MyApp())),
  );
}

Step 3 โ€” Add Navigation Observer

Add SentryNavigatorObserver to your MaterialApp or CupertinoApp:

import 'package:flutter/material.dart';
import 'package:sentry_flutter/sentry_flutter.dart';

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      navigatorObservers: [
        SentryNavigatorObserver(),
      ],
      // Always name your routes for Sentry to track them
      routes: {
        '/': (context) => HomeScreen(),
        '/profile': (context) => ProfileScreen(),
      },
    );
  }
}

For GoRouter:

import 'package:go_router/go_router.dart';
import 'package:sentry_flutter/sentry_flutter.dart';

final GoRouter router = GoRouter(
  observers: [SentryNavigatorObserver()],
  routes: [
    GoRoute(
      path: '/',
      name: 'home', // name is REQUIRED for Sentry route tracking
      builder: (context, state) => const HomeScreen(),
      routes: [
        GoRoute(
          path: 'profile/:id',
          name: 'profile', // name is REQUIRED
          builder: (context, state) => ProfileScreen(
            id: state.pathParameters['id']!,
          ),
        ),
      ],
    ),
  ],
);

Step 4 โ€” Configure Debug Symbol Upload

Readable stack traces in Sentry require uploading debug symbols when building with --obfuscate.

Add to pubspec.yaml:

dev_dependencies:
  sentry_dart_plugin: ^3.2.1

sentry:
  project: YOUR_PROJECT_SLUG
  org: YOUR_ORG_SLUG
  auth_token: YOUR_AUTH_TOKEN  # prefer SENTRY_AUTH_TOKEN env var instead
  upload_debug_symbols: true
  upload_sources: true
  upload_source_maps: true     # for Web

Build and upload:

# Android
flutter build apk \
  --release \
  --obfuscate \
  --split-debug-info=build/debug-info \
  --extra-gen-snapshot-options=--save-obfuscation-map=build/app/obfuscation.map.json
dart run sentry_dart_plugin

# iOS
flutter build ipa \
  --release \
  --obfuscate \
  --split-debug-info=build/debug-info \
  --extra-gen-snapshot-options=--save-obfuscation-map=build/app/obfuscation.map.json
dart run sentry_dart_plugin

# Web
flutter build web --release --source-maps
dart run sentry_dart_plugin

Path C: Manual โ€” Dart-Only (CLI / Server)

# pubspec.yaml
dependencies:
  sentry: ^9.14.0
import 'package:sentry/sentry.dart';

Future<void> main() async {
  await Sentry.init(
    (options) {
      options.dsn = 'YOUR_SENTRY_DSN';
      options.tracesSampleRate = 1.0;
      options.enableLogs = true;
    },
    appRunner: myApp,
  );
}

import 'package:sentry_flutter/sentry_flutter.dart';

Future<void> main() async {
  await SentryFlutter.init(
    (options) {
      options.dsn = 'YOUR_SENTRY_DSN';
      options.sendDefaultPii = true;

      // Environment โ€” detect release builds via dart.vm.product
      options.environment = const bool.fromEnvironment('dart.vm.product')
          ? 'production'
          : 'development';

      // Release is auto-set on iOS/Android as "packageName@version+build"
      // Override if needed:
      // options.release = 'my-app@1.0.0+42';

      // Error sampling โ€” reduce to drop a fraction of errors in high-volume production
      options.sampleRate = 1.0;

      // Tracing โ€” lower to 0.1โ€“0.2 in high-traffic production
      options.tracesSampleRate = 1.0;

      // Profiling โ€” iOS and macOS only (alpha); relative to tracesSampleRate
      options.profilesSampleRate = 1.0;

      // Session Replay โ€” iOS and Android only (SDK โ‰ฅ9.0.0)
      options.replay.sessionSampleRate = 0.1;   // record 10% of all sessions
      options.replay.onErrorSampleRate = 1.0;   // always record error sessions

      // Privacy defaults โ€” all text and images masked
      options.privacy.maskAllText = true;
      options.privacy.maskAllImages = true;

      // Structured logging (SDK โ‰ฅ9.5.0)
      options.enableLogs = true;

      // Attachments
      options.attachScreenshot = true;          // screenshot on error
      options.attachViewHierarchy = true;       // widget tree on error

      // HTTP client
      options.captureFailedRequests = true;     // auto-capture HTTP errors
      options.maxRequestBodySize = MaxRequestBodySize.small;

      // Android specifics
      options.anrEnabled = true;                // ANR detection
      options.enableNdkScopeSync = true;        // sync scope to native
      options.enableTombstone = false;          // Android 12+ tombstone (opt-in)

      // Navigation (Time to Full Display โ€” opt-in)
      options.enableTimeToFullDisplayTracing = true;
    },
    appRunner: () => runApp(SentryWidget(child: MyApp())),
  );
}

TTID (Time to Initial Display) is always enabled. TTFD is opt-in:

// Enable in options:
options.enableTimeToFullDisplayTracing = true;

Then report when your screen has loaded its data:

// Option 1: Widget wrapper (marks TTFD when child first renders)
SentryDisplayWidget(child: MyWidget())

// Option 2: Manual API call (after async data loads)
await _loadData();
SentryFlutter.currentDisplay()?.reportFullyDisplayed();

For Each Agreed Feature

Walk through features one at a time. Load the reference file for each, follow its steps, then verify before moving on:

FeatureReferenceLoad when...
Error Monitoring${SKILL_ROOT}/references/error-monitoring.mdAlways (baseline)
Tracing & Performance${SKILL_ROOT}/references/tracing.mdAlways โ€” navigation, HTTP, DB spans
Session Replay${SKILL_ROOT}/references/session-replay.mdiOS/Android user-facing apps
Profiling${SKILL_ROOT}/references/profiling.mdiOS/macOS performance-sensitive apps
Logging${SKILL_ROOT}/references/logging.mdStructured logging / log-trace correlation
Metrics${SKILL_ROOT}/references/metrics.mdCustom business metrics
Ecosystem Integrations${SKILL_ROOT}/references/ecosystem-integrations.mdHTTP clients, databases, GraphQL, state management

For each feature: Read ${SKILL_ROOT}/references/<feature>.md, follow steps exactly, verify it works.


Verification

After setup, test that Sentry is receiving events:

// Add a test button somewhere visible during development:
ElevatedButton(
  onPressed: () {
    throw Exception('Sentry test error!');
  },
  child: const Text('Test Sentry Error'),
)

// Or capture manually:
ElevatedButton(
  onPressed: () {
    Sentry.captureMessage('Sentry test message', level: SentryLevel.info);
  },
  child: const Text('Test Sentry Message'),
)

// Test structured logging:
ElevatedButton(
  onPressed: () {
    Sentry.logger.info('Test log from Flutter app');
  },
  child: const Text('Test Sentry Log'),
)

Check the Sentry dashboard:

  • Issues โ†’ test error should appear within seconds
  • Traces โ†’ look for a navigation transaction with child spans
  • Replays โ†’ session recording visible after app interaction (iOS/Android only)
  • Logs โ†’ structured log entries if enableLogs: true

โš ๏ธ Platform limitations in debug mode:

  • Native crashes, session replay, slow/frozen frames, and app start metrics only fully work in release builds on iOS/Android
  • Run flutter run --release or use a real device/emulator to test native features
  • Debug mode uses the Dart VM with JIT compilation โ€” some native integrations behave differently

After completing Flutter setup, check for a backend missing Sentry coverage:

# Adjacent backend directories
ls ../backend ../server ../api 2>/dev/null
cat ../go.mod 2>/dev/null | head -3
cat ../requirements.txt ../pyproject.toml 2>/dev/null | head -3
cat ../Gemfile 2>/dev/null | head -3
ls ../backend/package.json ../server/package.json 2>/dev/null

If a backend exists without Sentry, suggest the matching skill:

DetectedSuggest skill
Go backend (go.mod)sentry-go-sdk
Python backend (requirements.txt, pyproject.toml)sentry-python-sdk
Ruby backend (Gemfile)sentry-ruby-sdk
Node.js backendsentry-node-sdk
.NET backend (*.csproj)sentry-dotnet-sdk
React / Next.js websentry-react-sdk / sentry-nextjs-sdk

Distributed tracing โ€” if a backend skill is added, configure tracePropagationTargets in Flutter to propagate trace context to your API:

options.tracePropagationTargets = ['api.myapp.com', 'localhost'];
options.propagateTraceparent = true; // also send W3C traceparent header

This links mobile transactions to backend traces in the Sentry waterfall view.