sentry-flutter-sdk
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChineseAll 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, mobile error tracking, or Sentry for Fluttersentry_dart - User wants to monitor native crashes, ANRs, or app hangs on iOS/Android
Note: SDK versions and APIs below reflect≥9.14.0 (current stable, February 2026). Always verify against docs.sentry.io/platforms/flutter/ before implementing.sentry_flutter
- 用户要求“为Flutter添加Sentry”或在Flutter/Dart应用中“设置Sentry”
- 用户希望在Flutter中实现错误监控、追踪、性能分析、会话重放或日志功能
- 用户提到、
sentry_flutter、移动端错误追踪或Sentry for Fluttersentry_dart - 用户希望监控iOS/Android上的原生崩溃、ANR(应用无响应)或应用卡顿
注意: 以下SDK版本和API对应≥9.14.0(当前稳定版,2026年2月)。 实施前请务必对照docs.sentry.io/platforms/flutter/进行验证。sentry_flutter
Phase 1: Detect
阶段1:项目检测
Run these commands to understand the project before making any recommendations:
bash
undefined运行以下命令,在给出建议前先了解项目情况:
bash
undefinedDetect 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 and
Sentry.logger.*integrationsentry_logging - ⚡ Metrics — counters, gauges, distributions (open beta, SDK ≥9.11.0)
Platform limitations — be upfront:
| Feature | Platforms | Notes |
|---|---|---|
| Session Replay | iOS, Android | Not available on macOS, Linux, Windows, Web |
| Profiling | iOS, macOS | Alpha status; not available on Android, Linux, Windows, Web |
| Native crashes | iOS, Android, macOS | NDK/signal handling; Linux/Windows/Web: Dart exceptions only |
| App Start metrics | iOS, Android | Not available on desktop/web |
| Slow/frozen frames | iOS, Android, macOS | Not available on Linux, Windows, Web |
| Crons | N/A | Not 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、macOS | Alpha版本;不支持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 type | Recommended setup |
|---|---|
| Any Flutter app | Wizard CLI (handles pubspec, init, symbol upload) |
| Manual preferred | Path B below — |
| Dart-only (CLI, server) | Path C below — pure |
| 项目类型 | 推荐设置路径 |
|---|---|
| 任意Flutter应用 | 向导CLI(自动处理pubspec、初始化、符号上传) |
| 偏好手动设置 | 下方路径B —— |
| 纯Dart项目(CLI、服务器) | 下方路径C —— 仅使用 |
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:bashbrew install getsentry/tools/sentry-wizard && sentry-wizard -i flutterIt handles org/project selection, addstosentry_flutter, updatespubspec.yaml, configuresmain.dartfor debug symbol upload, and adds build scripts. Here's what it creates/modifies:sentry_dart_plugin
File Action Purpose pubspec.yamlAdds dependency andsentry_flutterconfig blocksentry:SDK + symbol upload config lib/main.dartWraps withmain()SentryFlutter.init()SDK initialization android/app/build.gradleAdds Proguard config reference Android obfuscation support .sentryclircAuth token and org/project config Symbol upload credentials Once it finishes, come back and skip to Verification.
If the user skips the wizard, proceed with Path B (Manual Setup) below.
需要你自行运行此命令 —— 向导会打开浏览器进行登录,需要交互式操作,无法由代理完成。请复制以下命令到终端执行:bashbrew 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_flutterOr add to manually:
pubspec.yamlyaml
dependencies:
flutter:
sdk: flutter
sentry_flutter: ^9.14.0Then run:
bash
flutter pub getStep 2 — Initialize Sentry in
lib/main.dartdart
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 to your or :
SentryNavigatorObserverMaterialAppCupertinoAppdart
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 .
--obfuscateAdd to :
pubspec.yamlyaml
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 WebBuild and upload:
bash
undefined步骤1 —— 安装SDK
bash
flutter pub add sentry_flutter或者手动添加到:
pubspec.yamlyaml
dependencies:
flutter:
sdk: flutter
sentry_flutter: ^9.14.0然后执行:
bash
flutter pub get步骤2 —— 在中初始化Sentry
lib/main.dartdart
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 —— 添加导航观察者
将添加到你的或:
SentryNavigatorObserverMaterialAppCupertinoAppdart
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.yamlyaml
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
undefinedAndroid
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
--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
--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
--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
--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
undefinedyaml
undefinedpubspec.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()快速参考:全功能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:
| Feature | Reference | Load when... |
|---|---|---|
| Error Monitoring | | Always (baseline) |
| Tracing & Performance | | Always — navigation, HTTP, DB spans |
| Session Replay | | iOS/Android user-facing apps |
| Profiling | | iOS/macOS performance-sensitive apps |
| Logging | | Structured logging / log-trace correlation |
| Metrics | | Custom business metrics (open beta) |
For each feature: , follow steps exactly, verify it works.
Read ${SKILL_ROOT}/references/<feature>.md逐个配置功能。加载每个功能的参考文件,按照步骤操作,然后验证功能是否正常:
| 功能 | 参考文件 | 加载时机 |
|---|---|---|
| 错误监控 | | 始终加载(基础功能) |
| 性能追踪 | | 始终加载 —— 导航、HTTP、数据库调用链 |
| 会话重放 | | iOS/Android端用户应用 |
| 性能分析 | | iOS/macOS端对性能敏感的应用 |
| 日志功能 | | 结构化日志 / 日志-追踪关联 |
| 指标监控 | | 自定义业务指标(开放测试版) |
对于每个功能:,严格按照步骤操作,验证功能正常。
阅读${SKILL_ROOT}/references/<feature>.mdConfiguration Reference
配置参考
Core SentryFlutter.init()
Options
SentryFlutter.init()核心SentryFlutter.init()
选项
SentryFlutter.init()| Option | Type | Default | Purpose |
|---|---|---|---|
| | — | Required. Project DSN. Env: |
| | — | e.g., |
| | Auto on iOS/Android | |
| | — | Distribution identifier; max 64 chars. Env: |
| | | Include PII: IP address, user labels, widget text in replay |
| | | Error event sampling (0.0–1.0) |
| | | Max breadcrumbs per event |
| | | Auto-attach stack traces to messages |
| | | Capture screenshot on error (mobile/desktop only) |
| enum | | Screenshot quality: |
| | | Attach JSON widget tree as attachment on error |
| | | Verbose SDK output. Never force |
| enum | | Log verbosity: |
| | | Disable SDK entirely (e.g., for testing) |
| | | Max offline-cached envelopes (not supported on Web) |
| | | Send SDK health reports (dropped events, etc.) |
| | | Report |
| | | Capture |
| | | Auto-finish idle user interaction transactions |
| 选项 | 类型 | 默认值 | 用途 |
|---|---|---|---|
| | — | 必填项。项目的数据源名称。可通过 |
| | — | 例如 |
| | iOS/Android自动生成 | 格式为 |
| | — | 发布版本标识符;最大64字符。可通过环境变量 |
| | | 是否包含个人身份信息:IP地址、用户标签、重放中的组件文本 |
| | | 错误事件采样率(0.0–1.0) |
| | | 每个事件最多保留的面包屑数量 |
| | | 自动为消息附加堆栈跟踪 |
| | | 发生错误时捕获截图(仅移动端/桌面端) |
| 枚举 | | 截图质量: |
| | | 发生错误时将JSON格式的组件树作为附件上传 |
| | 调试模式下为 | SDK详细日志输出。生产环境切勿强制设置为 |
| 枚举 | | 日志级别: |
| | | 完全禁用SDK(例如用于测试) |
| | | 离线缓存的最大信封数量(Web平台不支持) |
| | | 发送SDK健康报告(如丢弃的事件等) |
| | | 上报 |
| | | 捕获 |
| | | 用户无交互时自动结束事务的超时时间 |
Tracing Options
性能追踪选项
| Option | Type | Default | Purpose |
|---|---|---|---|
| | — | Transaction sample rate (0–1). Enable by setting >0 |
| | — | Per-transaction sampling; overrides |
| | — | URLs to attach |
| | | Also send W3C |
| | | Opt-in TTFD tracking per screen |
| | | Auto-enable performance monitoring |
| | | Create transactions for tap/click/long-press events |
| | | Breadcrumbs for every tracked user interaction |
| 选项 | 类型 | 默认值 | 用途 |
|---|---|---|---|
| | — | 事务采样率(0–1)。设置大于0的值以启用 |
| | — | 针对每个事务的采样逻辑;优先级高于 |
| | — | 需要附加 |
| | | 同时发送W3C |
| | | 手动开启每个屏幕的TTFD追踪 |
| | | 自动启用性能监控 |
| | | 为点击/长按等用户交互创建事务 |
| | | 为每个追踪到的用户交互添加面包屑 |
Profiling Options
性能分析选项
| Option | Type | Default | Purpose |
|---|---|---|---|
| | — | Profiling rate relative to |
| 选项 | 类型 | 默认值 | 用途 |
|---|---|---|---|
| | — | 性能分析采样率,基于 |
Native / Mobile Options
原生/移动端选项
| Option | Type | Default | Purpose |
|---|---|---|---|
| | | Auto-initialize native Android/iOS SDK layer |
| | | Capture native crashes (NDK, signal, Mach exception) |
| | | Sync Dart scope to Android NDK |
| | | Sync scope data to native SDKs |
| | | ANR detection (Android) |
| | | ANR timeout in milliseconds (Android) |
| | | OOM kill tracking (iOS) |
| | | Android 12+ native crash info via |
| | | Attach all threads on crash (Android) |
| | — | Native HTTP error capture, independent of Dart client (iOS/macOS, v9.11.0+) |
| | | App start timing instrumentation (iOS/Android) |
| | | Slow/frozen frame monitoring (iOS/Android/macOS) |
| | — | Proguard UUID for Android obfuscation mapping |
| 选项 | 类型 | 默认值 | 用途 |
|---|---|---|---|
| | | 自动初始化Android/iOS原生SDK层 |
| | | 捕获原生崩溃(NDK、信号、Mach异常) |
| | | 将Dart作用域同步到Android NDK |
| | | 将作用域数据同步到原生SDK |
| | | 启用ANR检测(Android) |
| | | ANR超时时间(毫秒,Android) |
| | | 启用OOM(内存不足)终止追踪(iOS) |
| | | 通过 |
| | | 崩溃时附加所有线程信息(Android) |
| | — | 捕获原生HTTP错误,独立于Dart客户端(iOS/macOS,v9.11.0+) |
| | | 应用启动时间检测(iOS/Android) |
| | | 慢帧/冻结帧监控(iOS/Android/macOS) |
| | — | Android混淆映射的Proguard UUID |
Session & Release Health Options
会话与版本健康选项
| Option | Type | Default | Purpose |
|---|---|---|---|
| | | Session tracking for crash-free user/session metrics |
| | | Background inactivity before session ends |
| 选项 | 类型 | 默认值 | 用途 |
|---|---|---|---|
| | | 会话追踪,用于统计无崩溃用户/会话指标 |
| | | 应用进入后台后,会话结束的无活动超时时间 |
Replay Options (options.replay
)
options.replay会话重放选项(options.replay
)
options.replay| Option | Type | Default | Purpose |
|---|---|---|---|
| | | Fraction of all sessions recorded |
| | | Fraction of error sessions recorded |
| 选项 | 类型 | 默认值 | 用途 |
|---|---|---|---|
| | | 记录的会话占总会话的比例 |
| | | 记录发生错误的会话占总错误会话的比例 |
Replay Privacy Options (options.privacy
)
options.privacy会话重放隐私选项(options.privacy
)
options.privacy| Option / Method | Default | Purpose |
|---|---|---|
| | Mask all text widget content |
| | Mask all image widgets |
| | Mask images from root asset bundle |
| — | Mask a specific widget type and all subclasses |
| — | Unmask a specific widget type |
| — | Custom masking decision per widget instance |
| 选项 / 方法 | 默认值 | 用途 |
|---|---|---|
| | 掩码所有文本组件内容 |
| | 掩码所有图片组件 |
| | 掩码根资源包中的图片 |
| — | 掩码特定类型的组件及其所有子类 |
| — | 取消掩码特定类型的组件 |
| — | 针对每个组件实例的自定义掩码逻辑 |
HTTP Options
HTTP选项
| Option | Type | Default | Purpose |
|---|---|---|---|
| | | Auto-capture HTTP errors |
| enum | | Body capture: |
| | | Status codes treated as failures |
| | | URL patterns to monitor |
| 选项 | 类型 | 默认值 | 用途 |
|---|---|---|---|
| | | 自动捕获HTTP错误 |
| 枚举 | | 请求体捕获策略: |
| | | 被视为失败请求的状态码范围 |
| | | 需要监控的URL模式 |
Hook Options
钩子选项
| Option | Type | Purpose |
|---|---|---|
| | Modify or drop error events. Return |
| | Modify or drop transaction events |
| | Process breadcrumbs before storage |
| | Filter structured logs before sending |
| 选项 | 类型 | 用途 |
|---|---|---|
| | 修改或丢弃错误事件。返回 |
| | 修改或丢弃事务事件 |
| | 存储前处理面包屑 |
| | 发送前过滤结构化日志 |
Environment Variables
环境变量
Pass via at build time:
--dart-define| Variable | Purpose | Notes |
|---|---|---|
| Data Source Name | Falls back from |
| Deployment environment | Falls back from |
| Release identifier | Falls back from |
| Build distribution | Falls back from |
| Upload debug symbols | Never embed in app — build tool only |
| Organization slug | Used by |
| Project slug | Used by |
Usage:
bash
flutter build apk --release \
--dart-define=SENTRY_DSN=https://xxx@sentry.io/123 \
--dart-define=SENTRY_ENVIRONMENT=productionThen in code:
dart
options.dsn = const String.fromEnvironment('SENTRY_DSN');
options.environment = const String.fromEnvironment('SENTRY_ENVIRONMENT', defaultValue: 'development');在构建时通过传递:
--dart-define| 变量 | 用途 | 说明 |
|---|---|---|
| 数据源名称 | 优先级低于 |
| 部署环境 | 优先级低于 |
| 版本标识符 | 优先级低于 |
| 发布版本 | 优先级低于 |
| 调试符号上传凭证 | 切勿嵌入到应用中 —— 仅用于构建工具 |
| 组织Slug | 供 |
| 项目Slug | 供 |
使用示例:
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 for deeper instrumentation:
sentry_flutter搭配安装以下包,实现更深度的检测:
sentry_flutterHTTP Clients
HTTP客户端
Standard package — built into , no extra install:
httpsentry_flutterdart
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_diobash
flutter pub add sentry_diodart
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)],
);标准包 —— 已内置到,无需额外安装:
httpsentry_flutterdart
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_diobash
flutter pub add sentry_diodart
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
数据库
| Package | Install | Setup |
|---|---|---|
| | |
| | |
| | Use |
| | Use |
| 包 | 安装命令 | 设置方式 |
|---|---|---|
| | |
| | |
| | 使用 |
| | 使用 |
Other
其他集成
| Package | Install | Purpose |
|---|---|---|
| | Dart |
| | GraphQL (gql, graphql_flutter, ferry) tracing |
| | Supabase query tracing (SDK ≥9.9.0) |
| | Feature flag tracking |
| | File I/O tracing via |
| 包 | 安装命令 | 用途 |
|---|---|---|
| | 将Dart |
| | GraphQL(gql、graphql_flutter、ferry)的追踪 |
| | Supabase查询追踪(SDK ≥9.9.0) |
| | 功能标志追踪 |
| | 通过 |
State Management Patterns
状态管理模式
No official packages — wire Sentry via observer APIs:
| Framework | Hook point | Pattern |
|---|---|---|
| BLoC/Cubit | | |
| Riverpod | | Fires for |
| Provider/ChangeNotifier | | Manually call |
| GetX | | |
暂无官方包——通过观察者API集成Sentry:
| 框架 | 钩子点 | 集成模式 |
|---|---|---|
| BLoC/Cubit | | 在 |
| Riverpod | | 针对 |
| Provider/ChangeNotifier | | 在catch块中手动调用 |
| GetX | | |
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
or use a real device/emulator to test native featuresflutter run --release- 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()| Integration | What it does |
|---|---|
| Captures |
| Catches unhandled Dart exceptions in runZonedGuarded |
| App start timing (iOS/Android) |
| Slow/frozen frames (iOS/Android/macOS) |
| User interaction breadcrumbs from native layer |
| Dart-layer tap/click transactions (requires |
| Device model, OS version, screen resolution |
| App version, build number, bundle ID |
| Network connectivity change breadcrumbs |
| Auto-instrument Dart |
| SDK metadata tagging |
| Auto-set release on iOS/Android from package info |
调用后,以下集成会自动激活,无需额外配置:
SentryFlutter.init()| 集成 | 功能 |
|---|---|
| 捕获 |
| 捕获runZonedGuarded中未处理的Dart异常 |
| 应用启动时间追踪(iOS/Android) |
| 慢帧/冻结帧监控(iOS/Android/macOS) |
| 来自原生层的用户交互面包屑 |
| Dart层的点击/长按事务(需要 |
| 设备型号、系统版本、屏幕分辨率 |
| 应用版本、构建号、包ID |
| 网络连接状态变化的面包屑 |
| 自动检测Dart |
| SDK元数据标记 |
| 在iOS/Android上自动从包信息中设置版本号 |
Phase 4: Cross-Link
阶段4:跨链接配置
After completing Flutter setup, check for a backend missing Sentry coverage:
bash
undefined完成Flutter设置后,检查是否存在未配置Sentry的后端:
bash
undefinedAdjacent 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 headerThis 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
故障排除
| Issue | Solution |
|---|---|
| Events not appearing in Sentry | Set |
| Ensure |
| Stack traces unreadable in Sentry | Upload debug symbols with |
| Stack traces missing on Web | Build with |
| Native crashes not captured | Confirm |
| Session replay not recording | iOS/Android only; confirm |
| Replay shows blank screens | Confirm |
| Profiling not working | iOS and macOS only (alpha); confirm |
| Navigation not tracked | Add |
| GoRouter routes unnamed | Add |
| TTFD never reports | Call |
| Set |
| Android ProGuard mapping missing | Ensure |
| iOS dSYM not uploaded | |
| |
| Hot restart crashes on Android debug | Known issue (fixed in SDK ≥9.9.0); upgrade if on older version |
| ANR detection too aggressive | Increase |
| Too many transactions in dashboard | Lower |
| Expected — |
| Crons not available | The Flutter/Dart SDK does not support Sentry Crons; use a server-side SDK instead |
| Metrics marked as experimental | |
| Wrap test widget with |
| Firebase Remote Config: Linux/Windows | |
| Isar tracing on Web | |
| 问题 | 解决方案 |
|---|---|
| 事件未出现在Sentry中 | 设置 |
| 确保 |
| Sentry中的堆栈跟踪不可读 | 使用 |
| Web平台的堆栈跟踪缺失 | 构建时添加 |
| 原生崩溃未被捕获 | 确认 |
| 会话重放未记录 | 仅支持iOS/Android;确认 |
| 会话重放显示空白屏幕 | 确认 |
| 性能分析无法工作 | 仅支持iOS和macOS(Alpha版本);确保已设置 |
| 导航未被追踪 | 将 |
| GoRouter路由未命名 | 为所有 |
| TTFD从未上报 | 在数据加载完成后调用 |
| 使用 |
| Android ProGuard映射缺失 | 确保添加了 |
| iOS dSYM未上传 | |
| |
| Android调试模式下热重启崩溃 | 已知问题(在SDK ≥9.9.0中已修复);如果使用旧版本请升级 |
| ANR检测过于灵敏 | 增大 |
| 仪表盘中事务过多 | 将 |
原生崩溃时 | 这是预期行为 —— |
| 定时任务(Crons)不可用 | Flutter/Dart SDK不支持Sentry Crons;请使用服务器端SDK |
| 指标监控标记为实验性 | |
测试中出现 | 在 |
| Firebase Remote Config:Linux/Windows | |
| Web平台的Isar追踪 | |