sentry-flutter-sdk

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese
All Skills > SDK Setup > Flutter SDK
所有技能 > SDK设置 > Flutter SDK

Sentry 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.
这是一个智能向导,会扫描你的Flutter或Dart项目,并引导你完成完整的Sentry设置——包括错误监控、追踪、会话重放、日志、性能分析以及生态系统集成。

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.

  • 用户要求“为Flutter添加Sentry”或在Flutter/Dart应用中“设置Sentry”
  • 用户希望在Flutter中实现错误监控、追踪、性能分析、会话重放或日志功能
  • 用户提到
    sentry_flutter
    sentry_dart
    、移动端错误追踪或Sentry for Flutter
  • 用户希望监控iOS/Android上的原生崩溃、ANR(应用无响应)或应用卡顿
注意: 以下SDK版本和API对应
sentry_flutter
≥9.14.0(当前稳定版,2026年2月)。 实施前请务必对照docs.sentry.io/platforms/flutter/进行验证。

Phase 1: Detect

阶段1:项目检测

Run these commands to understand the project before making any recommendations:
bash
undefined
运行以下命令,在给出建议前先了解项目情况:
bash
undefined

Detect Flutter project type and existing Sentry

检测Flutter项目类型及已有的Sentry配置

cat pubspec.yaml | grep -E '(sentry|flutter|dart)'
cat pubspec.yaml | grep -E '(sentry|flutter|dart)'

Check SDK version

检查SDK版本

cat pubspec.yaml | grep -A2 'environment:'
cat pubspec.yaml | grep -A2 'environment:'

Check for existing Sentry initialization

检查是否已初始化Sentry

grep -r "SentryFlutter.init|Sentry.init" lib/ 2>/dev/null | head -5
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
grep -E '(go_router|auto_route|get:|beamer|routemaster)' pubspec.yaml

Detect HTTP client

检测HTTP客户端

grep -E '(dio:|http:|chopper:)' pubspec.yaml
grep -E '(dio:|http:|chopper:)' pubspec.yaml

Detect database packages

检测数据库包

grep -E '(sqflite|drift|hive|isar|floor)' pubspec.yaml
grep -E '(sqflite|drift|hive|isar|floor)' pubspec.yaml

Detect state management (for integration patterns)

检测状态管理库(用于集成模式)

grep -E '(flutter_bloc|riverpod|provider:|get:)' pubspec.yaml
grep -E '(flutter_bloc|riverpod|provider:|get:)' pubspec.yaml

Detect GraphQL

检测GraphQL

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

Detect Firebase

检测Firebase

grep -E '(firebase_core|supabase)' pubspec.yaml
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
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:**

| Question | Impact |
|----------|--------|
| `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 |

---
ls android/ ios/ macos/ linux/ windows/ web/ 2>/dev/null

**需要确定的信息:**

| 问题 | 影响 |
|----------|--------|
| `pubspec.yaml`中已包含`sentry_flutter`? | 跳过安装步骤,直接进入功能配置 |
| Dart SDK版本≥3.5? | 这是`sentry_flutter` ≥9.0.0的必要条件 |
| 项目中存在`go_router`或`auto_route`? | 需要使用`SentryNavigatorObserver`——有特定的使用模式 |
| 项目中存在`dio`? | 建议集成`sentry_dio` |
| 项目中存在`sqflite`、`drift`、`hive`、`isar`? | 建议匹配对应的`sentry_*`数据库包 |
| 项目包含`android/`和`ios/`目录? | 可使用完整的移动端功能集 |
| 项目仅包含`web/`目录? | 无法使用会话重放和性能分析功能 |
| 项目包含`macos/`目录? | 可使用性能分析功能(Alpha版本) |
| 检测到后端目录? | 触发阶段4的跨链接配置 |

---

Phase 2: Recommend

阶段2:方案推荐

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 (open beta, 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)?"

根据检测结果给出具体建议,不要提出开放式问题——直接给出方案:
推荐配置(核心覆盖——务必设置以下内容):
  • 错误监控 —— 捕获Dart异常、Flutter框架错误以及原生崩溃(iOS + Android)
  • 性能追踪 —— 自动检测导航、应用启动、网络请求和UI交互
  • 会话重放 —— 捕获组件树截图以辅助调试(仅支持iOS + Android)
可选配置(增强可观测性):
  • 性能分析 —— CPU性能分析;仅支持iOS和macOS(Alpha版本)
  • 日志功能 —— 通过
    Sentry.logger.*
    sentry_logging
    集成实现结构化日志
  • 指标监控 —— 计数器、仪表盘、分布统计(开放测试版,SDK ≥9.11.0)
平台限制说明——请提前告知用户:
功能支持平台说明
会话重放iOS、Android不支持macOS、Linux、Windows、Web
性能分析iOS、macOSAlpha版本;不支持Android、Linux、Windows、Web
原生崩溃捕获iOS、Android、macOS基于NDK/信号处理;Linux/Windows/Web仅支持捕获Dart异常
应用启动指标iOS、Android不支持桌面/Web平台
慢帧/冻结帧监控iOS、Android、macOS不支持Linux、Windows、Web
定时任务(Crons)Flutter/Dart SDK不支持此功能
推荐话术示例:“针对你的iOS/Android版Flutter应用,我建议配置错误监控+性能追踪+会话重放功能。是否需要同时添加日志和性能分析(iOS/macOS Alpha版本)功能?”

Phase 3: Guide

阶段3:分步引导

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

项目类型推荐设置路径
任意Flutter应用向导CLI(自动处理pubspec、初始化、符号上传)
偏好手动设置下方路径B ——
pubspec.yaml
+
main.dart
纯Dart项目(CLI、服务器)下方路径C —— 仅使用
sentry

Path A: Wizard CLI (Recommended)

路径A:向导CLI(推荐)

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:
bash
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.yaml
Adds
sentry_flutter
dependency and
sentry:
config block
SDK + symbol upload config
lib/main.dart
Wraps
main()
with
SentryFlutter.init()
SDK initialization
android/app/build.gradle
Adds Proguard config referenceAndroid obfuscation support
.sentryclirc
Auth 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.

需要你自行运行此命令 —— 向导会打开浏览器进行登录,需要交互式操作,无法由代理完成。请复制以下命令到终端执行:
bash
brew install getsentry/tools/sentry-wizard && sentry-wizard -i flutter
该向导会处理组织/项目选择、将
sentry_flutter
添加到
pubspec.yaml
、更新
main.dart
、配置
sentry_dart_plugin
以上传调试符号,并添加构建脚本。它会创建/修改以下文件:
文件操作目的
pubspec.yaml
添加
sentry_flutter
依赖和
sentry:
配置块
SDK + 符号上传配置
lib/main.dart
SentryFlutter.init()
包裹
main()
SDK初始化
android/app/build.gradle
添加ProGuard配置引用支持Android代码混淆
.sentryclirc
配置认证令牌和组织/项目信息符号上传的凭证
完成后,请返回并跳转到验证步骤。
如果用户跳过向导,请继续执行路径B(手动设置)。

Path B: Manual — Flutter App

路径B:手动设置 —— Flutter应用

Step 1 — Install
bash
flutter pub add sentry_flutter
Or add to
pubspec.yaml
manually:
yaml
dependencies:
  flutter:
    sdk: flutter
  sentry_flutter: ^9.14.0
Then run:
bash
flutter pub get
Step 2 — Initialize Sentry in
lib/main.dart
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
:
dart
import 'package:flutter/material.dart';
import 'package:sentry_flutter/sentry_flutter.dart';

class MyApp extends StatelessWidget {
  
  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:
dart
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
:
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:
bash
undefined
步骤1 —— 安装SDK
bash
flutter pub add sentry_flutter
或者手动添加到
pubspec.yaml
yaml
dependencies:
  flutter:
    sdk: flutter
  sentry_flutter: ^9.14.0
然后执行:
bash
flutter pub get
步骤2 —— 在
lib/main.dart
中初始化Sentry
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;

      // 性能追踪
      options.tracesSampleRate = 1.0; // 生产环境建议降低至0.1–0.2

      // 性能分析(仅支持iOS和macOS —— Alpha版本)
      options.profilesSampleRate = 1.0;

      // 会话重放(仅支持iOS和Android)
      options.replay.sessionSampleRate = 0.1;
      options.replay.onErrorSampleRate = 1.0;

      // 结构化日志(SDK ≥9.5.0)
      options.enableLogs = true;

      options.environment = const bool.fromEnvironment('dart.vm.product')
          ? 'production'
          : 'development';
    },
    // 必须:包裹根组件以启用截图、重放和用户交互追踪
    appRunner: () => runApp(SentryWidget(child: MyApp())),
  );
}
步骤3 —— 添加导航观察者
SentryNavigatorObserver
添加到你的
MaterialApp
CupertinoApp
dart
import 'package:flutter/material.dart';
import 'package:sentry_flutter/sentry_flutter.dart';

class MyApp extends StatelessWidget {
  
  Widget build(BuildContext context) {
    return MaterialApp(
      navigatorObservers: [
        SentryNavigatorObserver(),
      ],
      // 务必为路由命名,以便Sentry追踪
      routes: {
        '/': (context) => HomeScreen(),
        '/profile': (context) => ProfileScreen(),
      },
    );
  }
}
对于GoRouter
dart
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', // 路由名称是Sentry追踪的必填项
      builder: (context, state) => const HomeScreen(),
      routes: [
        GoRoute(
          path: 'profile/:id',
          name: 'profile', // 路由名称是必填项
          builder: (context, state) => ProfileScreen(
            id: state.pathParameters['id']!,
          ),
        ),
      ],
    ),
  ],
);
步骤4 —— 配置调试符号上传
要在Sentry中查看可读的堆栈跟踪,使用
--obfuscate
构建时需要上传调试符号。
pubspec.yaml
中添加:
yaml
dev_dependencies:
  sentry_dart_plugin: ^3.2.1

sentry:
  project: YOUR_PROJECT_SLUG
  org: YOUR_ORG_SLUG
  auth_token: YOUR_AUTH_TOKEN  # 建议使用SENTRY_AUTH_TOKEN环境变量替代硬编码
  upload_debug_symbols: true
  upload_sources: true
  upload_source_maps: true     # 针对Web平台
构建并上传:
bash
undefined

Android

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
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

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
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

Web

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

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

---

Path C: Manual — Dart-Only (CLI / Server)

路径C:手动设置 —— 纯Dart项目(CLI / 服务器)

yaml
undefined
yaml
undefined

pubspec.yaml

pubspec.yaml

dependencies: sentry: ^9.14.0

```dart
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,
  );
}

dependencies: sentry: ^9.14.0

```dart
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,
  );
}

Quick Reference: Full-Featured
SentryFlutter.init()

快速参考:全功能
SentryFlutter.init()
配置

dart
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())),
  );
}

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

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

      // 环境 —— 通过dart.vm.product检测发布版本
      options.environment = const bool.fromEnvironment('dart.vm.product')
          ? 'production'
          : 'development';

      // 版本号在iOS/Android上自动设置为"packageName@version+build"
      // 如需自定义可覆盖:
      // options.release = 'my-app@1.0.0+42';

      // 错误采样率 —— 在高流量生产环境中可降低比例以减少上报量
      options.sampleRate = 1.0;

      // 性能追踪采样率 —— 高流量生产环境建议降低至0.1–0.2
      options.tracesSampleRate = 1.0;

      // 性能分析采样率 —— 仅支持iOS和macOS(Alpha版本);基于tracesSampleRate的相对比例
      options.profilesSampleRate = 1.0;

      // 会话重放 —— 仅支持iOS和Android(SDK ≥9.0.0)
      options.replay.sessionSampleRate = 0.1;   // 记录10%的所有会话
      options.replay.onErrorSampleRate = 1.0;   // 始终记录发生错误的会话

      // 隐私默认设置 —— 所有文本和图片都会被掩码处理
      options.privacy.maskAllText = true;
      options.privacy.maskAllImages = true;

      // 结构化日志(SDK ≥9.5.0)
      options.enableLogs = true;

      // 附件
      options.attachScreenshot = true;          // 发生错误时捕获截图
      options.attachViewHierarchy = true;       // 发生错误时附加组件树信息

      // HTTP客户端
      options.captureFailedRequests = true;     // 自动捕获HTTP错误
      options.maxRequestBodySize = MaxRequestBodySize.small;

      // Android特定配置
      options.anrEnabled = true;                // 启用ANR检测
      options.enableNdkScopeSync = true;        // 将作用域同步到原生层
      options.enableTombstone = false;          // Android 12+的崩溃墓碑信息(需手动开启)

      // 导航配置(全显示时间追踪 —— 需手动开启)
      options.enableTimeToFullDisplayTracing = true;
    },
    appRunner: () => runApp(SentryWidget(child: MyApp())),
  );
}

Navigation: Time to Full Display (TTFD)

导航:全显示时间(TTFD)追踪

TTID (Time to Initial Display) is always enabled. TTFD is opt-in:
dart
// Enable in options:
options.enableTimeToFullDisplayTracing = true;
Then report when your screen has loaded its data:
dart
// 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();

初始显示时间(TTID)默认已启用,全显示时间(TTFD)需要手动开启:
dart
// 在配置中启用:
options.enableTimeToFullDisplayTracing = true;
然后在屏幕加载完成数据后上报:
dart
// 方式1:组件包裹(当子组件首次渲染时标记TTFD)
SentryDisplayWidget(child: MyWidget())

// 方式2:手动调用API(异步数据加载完成后)
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.md
Always (baseline)
Tracing & Performance
${SKILL_ROOT}/references/tracing.md
Always — navigation, HTTP, DB spans
Session Replay
${SKILL_ROOT}/references/session-replay.md
iOS/Android user-facing apps
Profiling
${SKILL_ROOT}/references/profiling.md
iOS/macOS performance-sensitive apps
Logging
${SKILL_ROOT}/references/logging.md
Structured logging / log-trace correlation
Metrics
${SKILL_ROOT}/references/metrics.md
Custom business metrics (open beta)
For each feature:
Read ${SKILL_ROOT}/references/<feature>.md
, follow steps exactly, verify it works.

逐个配置功能。加载每个功能的参考文件,按照步骤操作,然后验证功能是否正常:
功能参考文件加载时机
错误监控
${SKILL_ROOT}/references/error-monitoring.md
始终加载(基础功能)
性能追踪
${SKILL_ROOT}/references/tracing.md
始终加载 —— 导航、HTTP、数据库调用链
会话重放
${SKILL_ROOT}/references/session-replay.md
iOS/Android端用户应用
性能分析
${SKILL_ROOT}/references/profiling.md
iOS/macOS端对性能敏感的应用
日志功能
${SKILL_ROOT}/references/logging.md
结构化日志 / 日志-追踪关联
指标监控
${SKILL_ROOT}/references/metrics.md
自定义业务指标(开放测试版)
对于每个功能:
阅读${SKILL_ROOT}/references/<feature>.md
,严格按照步骤操作,验证功能正常。

Configuration Reference

配置参考

Core
SentryFlutter.init()
Options

核心
SentryFlutter.init()
选项

OptionTypeDefaultPurpose
dsn
string
Required. Project DSN. Env:
SENTRY_DSN
via
--dart-define
environment
string
e.g.,
"production"
,
"staging"
. Env:
SENTRY_ENVIRONMENT
release
string
Auto on iOS/Android
"packageName@version+build"
. Env:
SENTRY_RELEASE
dist
string
Distribution identifier; max 64 chars. Env:
SENTRY_DIST
sendDefaultPii
bool
false
Include PII: IP address, user labels, widget text in replay
sampleRate
double
1.0
Error event sampling (0.0–1.0)
maxBreadcrumbs
int
100
Max breadcrumbs per event
attachStacktrace
bool
true
Auto-attach stack traces to messages
attachScreenshot
bool
false
Capture screenshot on error (mobile/desktop only)
screenshotQuality
enum
high
Screenshot quality:
full
,
high
,
medium
,
low
attachViewHierarchy
bool
false
Attach JSON widget tree as attachment on error
debug
bool
true
in debug
Verbose SDK output. Never force
true
in production
diagnosticLevel
enum
warning
Log verbosity:
debug
,
info
,
warning
,
error
,
fatal
enabled
bool
true
Disable SDK entirely (e.g., for testing)
maxCacheItems
int
30
Max offline-cached envelopes (not supported on Web)
sendClientReports
bool
true
Send SDK health reports (dropped events, etc.)
reportPackages
bool
true
Report
pubspec.yaml
dependency list
reportSilentFlutterErrors
bool
false
Capture
FlutterErrorDetails.silent
errors
idleTimeout
Duration
3000ms
Auto-finish idle user interaction transactions
选项类型默认值用途
dsn
string
必填项。项目的数据源名称。可通过
--dart-define
设置环境变量
SENTRY_DSN
environment
string
例如
"production"
"staging"
。可通过环境变量
SENTRY_ENVIRONMENT
设置
release
string
iOS/Android自动生成格式为
"packageName@version+build"
。可通过环境变量
SENTRY_RELEASE
设置
dist
string
发布版本标识符;最大64字符。可通过环境变量
SENTRY_DIST
设置
sendDefaultPii
bool
false
是否包含个人身份信息:IP地址、用户标签、重放中的组件文本
sampleRate
double
1.0
错误事件采样率(0.0–1.0)
maxBreadcrumbs
int
100
每个事件最多保留的面包屑数量
attachStacktrace
bool
true
自动为消息附加堆栈跟踪
attachScreenshot
bool
false
发生错误时捕获截图(仅移动端/桌面端)
screenshotQuality
枚举
high
截图质量:
full
high
medium
low
attachViewHierarchy
bool
false
发生错误时将JSON格式的组件树作为附件上传
debug
bool
调试模式下为
true
SDK详细日志输出。生产环境切勿强制设置为
true
diagnosticLevel
枚举
warning
日志级别:
debug
info
warning
error
fatal
enabled
bool
true
完全禁用SDK(例如用于测试)
maxCacheItems
int
30
离线缓存的最大信封数量(Web平台不支持)
sendClientReports
bool
true
发送SDK健康报告(如丢弃的事件等)
reportPackages
bool
true
上报
pubspec.yaml
中的依赖列表
reportSilentFlutterErrors
bool
false
捕获
FlutterErrorDetails.silent
类型的错误
idleTimeout
Duration
3000ms
用户无交互时自动结束事务的超时时间

Tracing Options

性能追踪选项

OptionTypeDefaultPurpose
tracesSampleRate
double
Transaction sample rate (0–1). Enable by setting >0
tracesSampler
function
Per-transaction sampling; overrides
tracesSampleRate
tracePropagationTargets
List
URLs to attach
sentry-trace
+
baggage
headers
propagateTraceparent
bool
false
Also send W3C
traceparent
header (SDK ≥9.7.0)
enableTimeToFullDisplayTracing
bool
false
Opt-in TTFD tracking per screen
enableAutoPerformanceTracing
bool
true
Auto-enable performance monitoring
enableUserInteractionTracing
bool
true
Create transactions for tap/click/long-press events
enableUserInteractionBreadcrumbs
bool
true
Breadcrumbs for every tracked user interaction
选项类型默认值用途
tracesSampleRate
double
事务采样率(0–1)。设置大于0的值以启用
tracesSampler
function
针对每个事务的采样逻辑;优先级高于
tracesSampleRate
tracePropagationTargets
List
需要附加
sentry-trace
+
baggage
头的URL列表
propagateTraceparent
bool
false
同时发送W3C
traceparent
头(SDK ≥9.7.0)
enableTimeToFullDisplayTracing
bool
false
手动开启每个屏幕的TTFD追踪
enableAutoPerformanceTracing
bool
true
自动启用性能监控
enableUserInteractionTracing
bool
true
为点击/长按等用户交互创建事务
enableUserInteractionBreadcrumbs
bool
true
为每个追踪到的用户交互添加面包屑

Profiling Options

性能分析选项

OptionTypeDefaultPurpose
profilesSampleRate
double
Profiling rate relative to
tracesSampleRate
. iOS/macOS only
选项类型默认值用途
profilesSampleRate
double
性能分析采样率,基于
tracesSampleRate
的相对比例。仅支持iOS/macOS

Native / Mobile Options

原生/移动端选项

OptionTypeDefaultPurpose
autoInitializeNativeSdk
bool
true
Auto-initialize native Android/iOS SDK layer
enableNativeCrashHandling
bool
true
Capture native crashes (NDK, signal, Mach exception)
enableNdkScopeSync
bool
true
Sync Dart scope to Android NDK
enableScopeSync
bool
true
Sync scope data to native SDKs
anrEnabled
bool
true
ANR detection (Android)
anrTimeoutInterval
int
5000
ANR timeout in milliseconds (Android)
enableWatchdogTerminationTracking
bool
true
OOM kill tracking (iOS)
enableTombstone
bool
false
Android 12+ native crash info via
ApplicationExitInfo
attachThreads
bool
false
Attach all threads on crash (Android)
captureNativeFailedRequests
bool
Native HTTP error capture, independent of Dart client (iOS/macOS, v9.11.0+)
enableAutoNativeAppStart
bool
true
App start timing instrumentation (iOS/Android)
enableFramesTracking
bool
true
Slow/frozen frame monitoring (iOS/Android/macOS)
proguardUuid
string
Proguard UUID for Android obfuscation mapping
选项类型默认值用途
autoInitializeNativeSdk
bool
true
自动初始化Android/iOS原生SDK层
enableNativeCrashHandling
bool
true
捕获原生崩溃(NDK、信号、Mach异常)
enableNdkScopeSync
bool
true
将Dart作用域同步到Android NDK
enableScopeSync
bool
true
将作用域数据同步到原生SDK
anrEnabled
bool
true
启用ANR检测(Android)
anrTimeoutInterval
int
5000
ANR超时时间(毫秒,Android)
enableWatchdogTerminationTracking
bool
true
启用OOM(内存不足)终止追踪(iOS)
enableTombstone
bool
false
通过
ApplicationExitInfo
获取Android 12+的原生崩溃信息
attachThreads
bool
false
崩溃时附加所有线程信息(Android)
captureNativeFailedRequests
bool
捕获原生HTTP错误,独立于Dart客户端(iOS/macOS,v9.11.0+)
enableAutoNativeAppStart
bool
true
应用启动时间检测(iOS/Android)
enableFramesTracking
bool
true
慢帧/冻结帧监控(iOS/Android/macOS)
proguardUuid
string
Android混淆映射的Proguard UUID

Session & Release Health Options

会话与版本健康选项

OptionTypeDefaultPurpose
enableAutoSessionTracking
bool
true
Session tracking for crash-free user/session metrics
autoSessionTrackingInterval
Duration
30s
Background inactivity before session ends
选项类型默认值用途
enableAutoSessionTracking
bool
true
会话追踪,用于统计无崩溃用户/会话指标
autoSessionTrackingInterval
Duration
30s
应用进入后台后,会话结束的无活动超时时间

Replay Options (
options.replay
)

会话重放选项(
options.replay

OptionTypeDefaultPurpose
replay.sessionSampleRate
double
0.0
Fraction of all sessions recorded
replay.onErrorSampleRate
double
0.0
Fraction of error sessions recorded
选项类型默认值用途
replay.sessionSampleRate
double
0.0
记录的会话占总会话的比例
replay.onErrorSampleRate
double
0.0
记录发生错误的会话占总错误会话的比例

Replay Privacy Options (
options.privacy
)

会话重放隐私选项(
options.privacy

Option / MethodDefaultPurpose
privacy.maskAllText
true
Mask all text widget content
privacy.maskAllImages
true
Mask all image widgets
privacy.maskAssetImages
true
Mask images from root asset bundle
privacy.mask<T>()
Mask a specific widget type and all subclasses
privacy.unmask<T>()
Unmask a specific widget type
privacy.maskCallback<T>()
Custom masking decision per widget instance
选项 / 方法默认值用途
privacy.maskAllText
true
掩码所有文本组件内容
privacy.maskAllImages
true
掩码所有图片组件
privacy.maskAssetImages
true
掩码根资源包中的图片
privacy.mask<T>()
掩码特定类型的组件及其所有子类
privacy.unmask<T>()
取消掩码特定类型的组件
privacy.maskCallback<T>()
针对每个组件实例的自定义掩码逻辑

HTTP Options

HTTP选项

OptionTypeDefaultPurpose
captureFailedRequests
bool
true
(Flutter)
Auto-capture HTTP errors
maxRequestBodySize
enum
never
Body capture:
never
,
small
,
medium
,
always
failedRequestStatusCodes
List
[500–599]
Status codes treated as failures
failedRequestTargets
List
['.*']
URL patterns to monitor
选项类型默认值用途
captureFailedRequests
bool
true
(Flutter)
自动捕获HTTP错误
maxRequestBodySize
枚举
never
请求体捕获策略:
never
small
medium
always
failedRequestStatusCodes
List
[500–599]
被视为失败请求的状态码范围
failedRequestTargets
List
['.*']
需要监控的URL模式

Hook Options

钩子选项

OptionTypePurpose
beforeSend
(SentryEvent, Hint) → SentryEvent?
Modify or drop error events. Return
null
to drop
beforeSendTransaction
(SentryEvent) → SentryEvent?
Modify or drop transaction events
beforeBreadcrumb
(Breadcrumb, Hint) → Breadcrumb?
Process breadcrumbs before storage
beforeSendLog
(SentryLog) → SentryLog?
Filter structured logs before sending

选项类型用途
beforeSend
(SentryEvent, Hint) → SentryEvent?
修改或丢弃错误事件。返回
null
表示丢弃
beforeSendTransaction
(SentryEvent) → SentryEvent?
修改或丢弃事务事件
beforeBreadcrumb
(Breadcrumb, Hint) → Breadcrumb?
存储前处理面包屑
beforeSendLog
(SentryLog) → SentryLog?
发送前过滤结构化日志

Environment Variables

环境变量

Pass via
--dart-define
at build time:
VariablePurposeNotes
SENTRY_DSN
Data Source NameFalls back from
options.dsn
SENTRY_ENVIRONMENT
Deployment environmentFalls back from
options.environment
SENTRY_RELEASE
Release identifierFalls back from
options.release
SENTRY_DIST
Build distributionFalls back from
options.dist
SENTRY_AUTH_TOKEN
Upload debug symbolsNever embed in app — build tool only
SENTRY_ORG
Organization slugUsed by
sentry_dart_plugin
SENTRY_PROJECT
Project slugUsed by
sentry_dart_plugin
Usage:
bash
flutter build apk --release \
  --dart-define=SENTRY_DSN=https://xxx@sentry.io/123 \
  --dart-define=SENTRY_ENVIRONMENT=production
Then in code:
dart
options.dsn = const String.fromEnvironment('SENTRY_DSN');
options.environment = const String.fromEnvironment('SENTRY_ENVIRONMENT', defaultValue: 'development');

在构建时通过
--dart-define
传递:
变量用途说明
SENTRY_DSN
数据源名称优先级低于
options.dsn
SENTRY_ENVIRONMENT
部署环境优先级低于
options.environment
SENTRY_RELEASE
版本标识符优先级低于
options.release
SENTRY_DIST
发布版本优先级低于
options.dist
SENTRY_AUTH_TOKEN
调试符号上传凭证切勿嵌入到应用中 —— 仅用于构建工具
SENTRY_ORG
组织Slug
sentry_dart_plugin
使用
SENTRY_PROJECT
项目Slug
sentry_dart_plugin
使用
使用示例:
bash
flutter build apk --release \
  --dart-define=SENTRY_DSN=https://xxx@sentry.io/123 \
  --dart-define=SENTRY_ENVIRONMENT=production
然后在代码中读取:
dart
options.dsn = const String.fromEnvironment('SENTRY_DSN');
options.environment = const String.fromEnvironment('SENTRY_ENVIRONMENT', defaultValue: 'development');

Ecosystem Integrations

生态系统集成

Add these packages alongside
sentry_flutter
for deeper instrumentation:
搭配
sentry_flutter
安装以下包,实现更深度的检测:

HTTP Clients

HTTP客户端

Standard
http
package
— built into
sentry_flutter
, no extra install:
dart
import 'package:sentry/sentry.dart';

// Wrap your http client
final client = SentryHttpClient(
  captureFailedRequests: true,
  failedRequestStatusCodes: [SentryStatusCode.range(400, 599)],
);
try {
  final response = await client.get(Uri.parse('https://api.example.com/users'));
} finally {
  client.close();
}
Dio — install
sentry_dio
:
bash
flutter pub add sentry_dio
dart
import 'package:dio/dio.dart';
import 'package:sentry_dio/sentry_dio.dart';

final dio = Dio();
// Add your interceptors first, THEN addSentry() last
dio.addSentry(
  captureFailedRequests: true,
  failedRequestStatusCodes: [SentryStatusCode.range(400, 599)],
);
标准
http
—— 已内置到
sentry_flutter
,无需额外安装:
dart
import 'package:sentry/sentry.dart';

// 包裹你的http客户端
final client = SentryHttpClient(
  captureFailedRequests: true,
  failedRequestStatusCodes: [SentryStatusCode.range(400, 599)],
);
try {
  final response = await client.get(Uri.parse('https://api.example.com/users'));
} finally {
  client.close();
}
Dio —— 安装
sentry_dio
bash
flutter pub add sentry_dio
dart
import 'package:dio/dio.dart';
import 'package:sentry_dio/sentry_dio.dart';

final dio = Dio();
// 先添加你的拦截器,最后添加addSentry()
dio.addSentry(
  captureFailedRequests: true,
  failedRequestStatusCodes: [SentryStatusCode.range(400, 599)],
);

Databases

数据库

PackageInstallSetup
sentry_sqflite
flutter pub add sentry_sqflite
databaseFactory = SentrySqfliteDatabaseFactory();
sentry_drift
flutter pub add sentry_drift
.interceptWith(SentryQueryInterceptor(databaseName: 'db'))
sentry_hive
flutter pub add sentry_hive
Use
SentryHive
instead of
Hive
sentry_isar
flutter pub add sentry_isar
Use
SentryIsar.open()
instead of
Isar.open()
安装命令设置方式
sentry_sqflite
flutter pub add sentry_sqflite
databaseFactory = SentrySqfliteDatabaseFactory();
sentry_drift
flutter pub add sentry_drift
.interceptWith(SentryQueryInterceptor(databaseName: 'db'))
sentry_hive
flutter pub add sentry_hive
使用
SentryHive
替代
Hive
sentry_isar
flutter pub add sentry_isar
使用
SentryIsar.open()
替代
Isar.open()

Other

其他集成

PackageInstallPurpose
sentry_logging
flutter pub add sentry_logging
Dart
logging
package → Sentry breadcrumbs/events
sentry_link
flutter pub add sentry_link
GraphQL (gql, graphql_flutter, ferry) tracing
sentry_supabase
flutter pub add sentry_supabase
Supabase query tracing (SDK ≥9.9.0)
sentry_firebase_remote_config
flutter pub add sentry_firebase_remote_config
Feature flag tracking
sentry_file
flutter pub add sentry_file
File I/O tracing via
.sentryTrace()
extension
安装命令用途
sentry_logging
flutter pub add sentry_logging
将Dart
logging
包的日志转为Sentry面包屑/事件
sentry_link
flutter pub add sentry_link
GraphQL(gql、graphql_flutter、ferry)的追踪
sentry_supabase
flutter pub add sentry_supabase
Supabase查询追踪(SDK ≥9.9.0)
sentry_firebase_remote_config
flutter pub add sentry_firebase_remote_config
功能标志追踪
sentry_file
flutter pub add sentry_file
通过
.sentryTrace()
扩展实现文件I/O追踪

State Management Patterns

状态管理模式

No official packages — wire Sentry via observer APIs:
FrameworkHook pointPattern
BLoC/Cubit
BlocObserver.onError
Sentry.captureException(error, stackTrace: stackTrace)
inside
onError
; set
Bloc.observer = SentryBlocObserver()
before init
Riverpod
ProviderObserver.providerDidFail
Fires for
FutureProvider
/
StreamProvider
failures; wrap app with
ProviderScope(observers: [SentryProviderObserver()])
Provider/ChangeNotifier
try/catch
in
notifyListeners
callers
Manually call
Sentry.captureException(e, stackTrace: stack)
in catch blocks
GetX
GetMaterialApp.onError
GetMaterialApp(onError: (details) => Sentry.captureException(...))

暂无官方包——通过观察者API集成Sentry:
框架钩子点集成模式
BLoC/Cubit
BlocObserver.onError
onError
中调用
Sentry.captureException(error, stackTrace: stackTrace)
;初始化前设置
Bloc.observer = SentryBlocObserver()
Riverpod
ProviderObserver.providerDidFail
针对
FutureProvider
/
StreamProvider
的失败事件触发;用
ProviderScope(observers: [SentryProviderObserver()])
包裹应用
Provider/ChangeNotifier
notifyListeners
调用处的
try/catch
在catch块中手动调用
Sentry.captureException(e, stackTrace: stack)
GetX
GetMaterialApp.onError
GetMaterialApp(onError: (details) => Sentry.captureException(...))

Production Settings

生产环境设置

Lower sample rates and harden config before shipping:
dart
Future<void> main() async {
  final isProduction = const bool.fromEnvironment('dart.vm.product');

  await SentryFlutter.init(
    (options) {
      options.dsn = const String.fromEnvironment('SENTRY_DSN');
      options.environment = isProduction ? 'production' : 'development';

      // Trace 10% of transactions in high-traffic production
      options.tracesSampleRate = isProduction ? 0.1 : 1.0;

      // Profile 100% of traced transactions (profiling is always a subset)
      options.profilesSampleRate = 1.0;

      // Replay all error sessions, sample 5% of normal sessions
      options.replay.onErrorSampleRate = 1.0;
      options.replay.sessionSampleRate = isProduction ? 0.05 : 1.0;

      // Disable debug logging in production
      options.debug = !isProduction;
    },
    appRunner: () => runApp(SentryWidget(child: MyApp())),
  );
}

在发布前降低采样率并强化配置:
dart
Future<void> main() async {
  final isProduction = const bool.fromEnvironment('dart.vm.product');

  await SentryFlutter.init(
    (options) {
      options.dsn = const String.fromEnvironment('SENTRY_DSN');
      options.environment = isProduction ? 'production' : 'development';

      // 高流量生产环境中仅追踪10%的事务
      options.tracesSampleRate = isProduction ? 0.1 : 1.0;

      // 对所有已追踪的事务进行性能分析(性能分析始终是追踪的子集)
      options.profilesSampleRate = 1.0;

      // 记录所有发生错误的会话,采样5%的正常会话
      options.replay.onErrorSampleRate = 1.0;
      options.replay.sessionSampleRate = isProduction ? 0.05 : 1.0;

      // 生产环境禁用调试日志
      options.debug = !isProduction;
    },
    appRunner: () => runApp(SentryWidget(child: MyApp())),
  );
}

Verification

验证

After setup, test that Sentry is receiving events:
dart
// 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

设置完成后,测试Sentry是否能接收事件:
dart
// 在开发环境中添加一个可见的测试按钮:
ElevatedButton(
  onPressed: () {
    throw Exception('Sentry测试错误!');
  },
  child: const Text('测试Sentry错误'),
)

// 或者手动捕获:
ElevatedButton(
  onPressed: () {
    Sentry.captureMessage('Sentry测试消息', level: SentryLevel.info);
  },
  child: const Text('测试Sentry消息'),
)

// 测试结构化日志:
ElevatedButton(
  onPressed: () {
    Sentry.logger.info('来自Flutter应用的测试日志');
  },
  child: const Text('测试Sentry日志'),
)
检查Sentry仪表盘:
  • 问题 → 测试错误应在几秒内出现
  • 追踪 → 查找包含子调用链的导航事务
  • 重放 → 应用交互后可查看会话记录(仅iOS/Android)
  • 日志 → 如果
    enableLogs: true
    ,可看到结构化日志条目
⚠️ 调试模式下的平台限制:
  • 原生崩溃、会话重放、慢帧/冻结帧、应用启动指标仅在iOS/Android的发布版本中完全生效
  • 运行
    flutter run --release
    或使用真实设备/模拟器测试原生功能
  • 调试模式使用Dart VM的JIT编译——部分原生集成的行为会有所不同

Default Auto-Enabled Integrations

默认自动启用的集成

These are active with no extra config when you call
SentryFlutter.init()
:
IntegrationWhat it does
FlutterErrorIntegration
Captures
FlutterError.onError
framework errors
RunZonedGuardedIntegration
Catches unhandled Dart exceptions in runZonedGuarded
NativeAppStartIntegration
App start timing (iOS/Android)
FramesTrackingIntegration
Slow/frozen frames (iOS/Android/macOS)
NativeUserInteractionIntegration
User interaction breadcrumbs from native layer
UserInteractionIntegration
Dart-layer tap/click transactions (requires
SentryWidget
)
DeviceContextIntegration
Device model, OS version, screen resolution
AppContextIntegration
App version, build number, bundle ID
ConnectivityIntegration
Network connectivity change breadcrumbs
HttpClientIntegration
Auto-instrument Dart
http
requests
SdkIntegration
SDK metadata tagging
ReleaseIntegration
Auto-set release on iOS/Android from package info

调用
SentryFlutter.init()
后,以下集成会自动激活,无需额外配置:
集成功能
FlutterErrorIntegration
捕获
FlutterError.onError
框架错误
RunZonedGuardedIntegration
捕获runZonedGuarded中未处理的Dart异常
NativeAppStartIntegration
应用启动时间追踪(iOS/Android)
FramesTrackingIntegration
慢帧/冻结帧监控(iOS/Android/macOS)
NativeUserInteractionIntegration
来自原生层的用户交互面包屑
UserInteractionIntegration
Dart层的点击/长按事务(需要
SentryWidget
DeviceContextIntegration
设备型号、系统版本、屏幕分辨率
AppContextIntegration
应用版本、构建号、包ID
ConnectivityIntegration
网络连接状态变化的面包屑
HttpClientIntegration
自动检测Dart
http
请求
SdkIntegration
SDK元数据标记
ReleaseIntegration
在iOS/Android上自动从包信息中设置版本号

Phase 4: Cross-Link

阶段4:跨链接配置

After completing Flutter setup, check for a backend missing Sentry coverage:
bash
undefined
完成Flutter设置后,检查是否存在未配置Sentry的后端:
bash
undefined

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:

| Detected | Suggest 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 backend | `sentry-node-sdk` |
| .NET backend (`*.csproj`) | `sentry-dotnet-sdk` |
| React / Next.js web | `sentry-react-sdk` / `sentry-nextjs-sdk` |

**Distributed tracing** — if a backend skill is added, configure `tracePropagationTargets` in Flutter to propagate trace context to your API:

```dart
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.

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

如果检测到未配置Sentry的后端,建议使用对应的技能:

| 检测到的后端 | 建议使用的技能 |
|----------|--------------|
| Go后端(`go.mod`) | `sentry-go-sdk` |
| Python后端(`requirements.txt`, `pyproject.toml`) | `sentry-python-sdk` |
| Ruby后端(`Gemfile`) | `sentry-ruby-sdk` |
| Node.js后端 | `sentry-node-sdk` |
| .NET后端(`*.csproj`) | `sentry-dotnet-sdk` |
| React / Next.js Web应用 | `sentry-react-sdk` / `sentry-nextjs-sdk` |

**分布式追踪** —— 如果添加了后端技能,在Flutter中配置`tracePropagationTargets`以将追踪上下文传递到你的API:

```dart
options.tracePropagationTargets = ['api.myapp.com', 'localhost'];
options.propagateTraceparent = true; // 同时发送W3C traceparent头
这会在Sentry的瀑布视图中将移动端事务与后端追踪关联起来。

Troubleshooting

故障排除

IssueSolution
Events not appearing in SentrySet
options.debug = true
— SDK logs to Flutter console; verify DSN is correct
SentryFlutter.init
throws
Ensure
main()
is
async
and you
await SentryFlutter.init(...)
Stack traces unreadable in SentryUpload debug symbols with
sentry_dart_plugin
; build with
--obfuscate --split-debug-info
Stack traces missing on WebBuild with
--source-maps
and run
dart run sentry_dart_plugin
to upload
Native crashes not capturedConfirm
enableNativeCrashHandling: true
; test in release mode, not debug
Session replay not recordingiOS/Android only; confirm
SentryWidget
wraps root; check
replay.onErrorSampleRate
Replay shows blank screensConfirm
SentryWidget(child: MyApp())
is outermost widget; not inside navigator
Profiling not workingiOS and macOS only (alpha); confirm
tracesSampleRate > 0
is set first
Navigation not trackedAdd
SentryNavigatorObserver()
to
navigatorObservers
; name all routes
GoRouter routes unnamedAdd
name:
to all
GoRoute
entries — unnamed routes are tracked as
null
TTFD never reportsCall
SentryFlutter.currentDisplay()?.reportFullyDisplayed()
after data loads, or wrap with
SentryDisplayWidget
sentry_dart_plugin
auth error
Set
SENTRY_AUTH_TOKEN
env var instead of hardcoding in
pubspec.yaml
Android ProGuard mapping missingEnsure
--extra-gen-snapshot-options=--save-obfuscation-map=...
flag is set
iOS dSYM not uploaded
sentry_dart_plugin
handles this; check
upload_debug_symbols: true
in
pubspec.yaml
sentry:
block
pub get
fails: Dart SDK too old
sentry_flutter
≥9.0.0 requires Dart ≥3.5.0; run
flutter upgrade
Hot restart crashes on Android debugKnown issue (fixed in SDK ≥9.9.0); upgrade if on older version
ANR detection too aggressiveIncrease
anrTimeoutInterval
(default: 5000ms)
Too many transactions in dashboardLower
tracesSampleRate
to
0.1
or use
tracesSampler
to drop health checks
beforeSend
not firing for native crashes
Expected —
beforeSend
intercepts only Dart-layer events; native crashes bypass it
Crons not availableThe Flutter/Dart SDK does not support Sentry Crons; use a server-side SDK instead
Metrics marked as experimental
sentry_flutter
Metrics API is open beta (SDK ≥9.11.0); stable on other SDKs
SentryWidget
warning in tests
Wrap test widget with
SentryFlutter.init()
in
setUpAll
, or use
enabled: false
Firebase Remote Config: Linux/Windows
sentry_firebase_remote_config
not supported on Linux/Windows (Firebase limitation)
Isar tracing on Web
sentry_isar
does NOT support Web (Isar does not support Web)
问题解决方案
事件未出现在Sentry中设置
options.debug = true
—— SDK会将日志输出到Flutter控制台;验证DSN是否正确
SentryFlutter.init
抛出异常
确保
main()
async
函数,并且你使用了
await SentryFlutter.init(...)
Sentry中的堆栈跟踪不可读使用
sentry_dart_plugin
上传调试符号;构建时添加
--obfuscate --split-debug-info
参数
Web平台的堆栈跟踪缺失构建时添加
--source-maps
参数,然后运行
dart run sentry_dart_plugin
上传
原生崩溃未被捕获确认
enableNativeCrashHandling: true
;在发布版本中测试,而非调试版本
会话重放未记录仅支持iOS/Android;确认
SentryWidget
包裹了根组件;检查
replay.onErrorSampleRate
配置
会话重放显示空白屏幕确认
SentryWidget(child: MyApp())
是最外层组件;不要放在导航器内部
性能分析无法工作仅支持iOS和macOS(Alpha版本);确保已设置
tracesSampleRate > 0
导航未被追踪
SentryNavigatorObserver()
添加到
navigatorObservers
;为所有路由命名
GoRouter路由未命名为所有
GoRoute
条目添加
name:
—— 未命名的路由会被追踪为
null
TTFD从未上报在数据加载完成后调用
SentryFlutter.currentDisplay()?.reportFullyDisplayed()
,或使用
SentryDisplayWidget
包裹组件
sentry_dart_plugin
认证错误
使用
SENTRY_AUTH_TOKEN
环境变量替代在
pubspec.yaml
中硬编码
Android ProGuard映射缺失确保添加了
--extra-gen-snapshot-options=--save-obfuscation-map=...
参数
iOS dSYM未上传
sentry_dart_plugin
会自动处理;检查
pubspec.yaml
sentry:
块中是否设置了
upload_debug_symbols: true
pub get
失败:Dart SDK版本过旧
sentry_flutter
≥9.0.0需要Dart ≥3.5.0;运行
flutter upgrade
升级
Android调试模式下热重启崩溃已知问题(在SDK ≥9.9.0中已修复);如果使用旧版本请升级
ANR检测过于灵敏增大
anrTimeoutInterval
(默认:5000ms)
仪表盘中事务过多
tracesSampleRate
降低至
0.1
,或使用
tracesSampler
丢弃健康检查类事务
原生崩溃时
beforeSend
未触发
这是预期行为 ——
beforeSend
仅拦截Dart层的事件;原生崩溃会绕过它
定时任务(Crons)不可用Flutter/Dart SDK不支持Sentry Crons;请使用服务器端SDK
指标监控标记为实验性
sentry_flutter
的Metrics API是开放测试版(SDK ≥9.11.0);在其他SDK中已稳定
测试中出现
SentryWidget
警告
setUpAll
中用
SentryFlutter.init()
包裹测试组件,或设置
enabled: false
Firebase Remote Config:Linux/Windows
sentry_firebase_remote_config
不支持Linux/Windows(Firebase的限制)
Web平台的Isar追踪
sentry_isar
不支持Web(Isar本身不支持Web)