关于 sentry-flutter-sdk
用于在 Flutter 和 Dart 项目中配置 Sentry 的技能。它会扫描项目并引导开发者设置监控、性能跟踪及相关集成,同时说明平台限制。
主要功能
- 01扫描 Flutter 和 Dart 项目配置
- 02引导安装并初始化 SDK
- 03配置错误监控与跟踪
- 04涵盖回放、分析、日志和指标
- 05说明各平台的功能限制
适用场景
- 01为现有 Flutter 应用添加 Sentry
- 02为 Dart 命令行程序或服务配置监控
- 03为 iOS 或 Android 应用选择监控功能
安装
复制下面的命令,在终端中运行。
npx skills add https:/ / github.com/ getsentry/ sentry-for-ai --skill sentry-flutter-sdk安装后在 Claude Code 中输入/sentry-flutter-sdk确认已加载。
包含的文件
除 SKILL.md 外,安装时一起下载的参考资料和脚本。
references/ecosystem-integrations.mderror-monitoring.mdlogging.mdmetrics.mdprofiling.mdsession-replay.mdtracing.md详细介绍
Sentry Flutter SDK
一款观点鲜明的向导,可扫描你的 Flutter 或 Dart 项目,并引导你完成 Sentry 的完整设置——错误监控、追踪、会话回放、日志记录、性能分析和生态集成。
在以下情况下调用此技能
- 用户要求“在 Flutter 中添加 Sentry”或“设置 Sentry”
- 用户想在 Flutter 中使用错误监控、追踪、性能分析、会话回放或日志记录
- 用户提到
sentry_flutter、sentry_dart、移动端错误追踪或 Flutter 版 Sentry - 用户想监控 iOS/Android 上的原生崩溃、ANR 或应用卡死
注意: 以下 SDK 版本和 API 反映的是
sentry_flutter≥9.14.0(当前稳定版,2026 年 2 月)。 实施前,请务必对照 docs.sentry.io/platforms/flutter/ 进行验证。
阶段 1:检测
在提出任何建议之前,运行以下命令以了解项目:
# 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
需要确定的事项:
| 问题 | 影响 |
|---|---|
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 阶段交叉链接 |
阶段 2:建议
根据你的发现提出具体建议。不要提出开放式问题——直接给出方案:
建议(核心覆盖——始终设置以下功能):
- ✅ 错误监控——捕获 Dart 异常、Flutter 框架错误和原生崩溃(iOS + Android)
- ✅ 追踪——自动检测导航、应用启动、网络请求和 UI 交互
- ✅ 会话回放——捕获 widget 树截图以便调试(仅限 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 版)吗?”
阶段 3:引导
确定设置路径
| 项目类型 | 建议设置方式 |
|---|---|
| 任意 Flutter 应用 | 向导 CLI(处理 pubspec、初始化和符号上传) |
| 倾向手动设置 | 以下路径 B——pubspec.yaml + main.dart |
| 仅 Dart(CLI、服务端) | 以下路径 C——纯 sentry 包 |
路径 A:向导 CLI(推荐)
你需要自行运行——向导会打开浏览器供你登录,并要求进行 Agent 无法处理的交互式输入。请复制并粘贴到终端中:
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(手动设置)。
路径 B:手动设置 — Flutter 应用
步骤 1 — 安装
flutter pub add sentry_flutter
或者手动添加到 pubspec.yaml:
dependencies:
flutter:
sdk: flutter
sentry_flutter: ^9.14.0
然后运行:
flutter pub get
步骤 2 — 在 lib/main.dart 中初始化 Sentry
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())),
);
}
步骤 3 — 添加导航观察器
将 SentryNavigatorObserver 添加到 MaterialApp 或 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(),
},
);
}
}
对于 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']!,
),
),
],
),
],
);
步骤 4 — 配置调试符号上传
使用 --obfuscate 构建时,需要上传调试符号,Sentry 才能显示可读的堆栈跟踪。
添加到 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
构建并上传:
# 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
路径 C:手动设置 — 纯 Dart(CLI / 服务端)
# 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,
);
}
快速参考:功能完整的 SentryFlutter.init()
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 = '[email protected]+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())),
);
}
导航:完整显示时间(TTFD)
TTID(初始显示时间)始终启用。TTFD 为可选功能:
// Enable in options:
options.enableTimeToFullDisplayTracing = true;
然后,在屏幕加载完数据后进行报告:
// 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();
每项约定的功能
一次配置一项功能。针对每项功能加载参考文件,按步骤操作,然后在继续之前进行验证:
| 功能 | 参考文档 | 在以下情况下加载…… |
|---|---|---|
| 错误监控 | ${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/ecosystem-integrations.md | HTTP 客户端、数据库、GraphQL、状态管理 |
对于每项功能:Read ${SKILL_ROOT}/references/<feature>.md,严格按照步骤操作,并验证其是否正常运行。
配置参考
核心 SentryFlutter.init() 选项
| 选项 | 类型 | 默认值 | 用途 |
|---|---|---|---|
dsn | string | — | 必填。 项目 DSN。环境变量:通过 --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 | 包含个人身份信息(PII):IP 地址、用户标签、重放中的组件文本 |
sampleRate | double | 1.0 | 错误事件采样率(0.0–1.0) |
maxBreadcrumbs | int | 100 | 每个事件的面包屑上限 |
attachStacktrace | bool | true | 自动将堆栈跟踪附加到消息 |
attachScreenshot | bool | false | 发生错误时截取屏幕截图(仅限移动端/桌面端) |
screenshotQuality | enum | high | 屏幕截图质量:full、high、medium、low |
attachViewHierarchy | bool | false | 发生错误时将 JSON 组件树作为附件 |
debug | bool | 调试模式下为 true | 输出详细的 SDK 信息。生产环境中切勿强制设为 true |
diagnosticLevel | enum | 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 | 自动结束空闲的用户交互事务 |
追踪选项
| 选项 | 类型 | 默认值 | 用途 |
|---|---|---|---|
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 | 为每次被跟踪的用户交互添加面包屑 |
性能分析选项
| 选项 | 类型 | 默认值 | 用途 |
|---|---|---|---|
profilesSampleRate | double | — | 相对于 tracesSampleRate 的性能分析采样率。仅限 iOS/macOS |
原生/移动端选项
| 选项 | 类型 | 默认值 | 用途 |
|---|---|---|---|
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 |
会话与版本健康度选项
| 选项 | 类型 | 默认值 | 用途 |
|---|---|---|---|
enableAutoSessionTracking | bool | true | 跟踪会话,以统计无崩溃的用户/会话指标 |
autoSessionTrackingInterval | Duration | 30s | 会话结束前的后台非活动时长 |
回放选项(options.replay)
| 选项 | 类型 | 默认值 | 用途 |
|---|---|---|---|
replay.sessionSampleRate | double | 0.0 | 录制的会话占全部会话的比例 |
replay.onErrorSampleRate | double | 0.0 | 录制的错误会话所占比例 |
回放隐私选项(options.privacy)
| 选项/方法 | 默认值 | 用途 |
|---|---|---|
privacy.maskAllText | true | 遮蔽所有文本组件的内容 |
privacy.maskAllImages | true | 遮蔽所有图像组件 |
privacy.maskAssetImages | true | 遮蔽根资源包中的图像 |
privacy.mask<T>() | — | 遮蔽特定组件类型及其所有子类 |
privacy.unmask<T>() | — | 取消遮蔽特定组件类型 |
privacy.maskCallback<T>() | — | 针对每个组件实例自定义遮蔽判定 |
HTTP 选项
| 选项 | 类型 | 默认值 | 用途 |
|---|---|---|---|
captureFailedRequests | bool | true(Flutter) | 自动捕获 HTTP 错误 |
maxRequestBodySize | enum | never | 请求正文捕获:never、small、medium、always |
failedRequestStatusCodes | List | [500–599] | 视为失败的状态码 |
failedRequestTargets | List | ['.*'] | 要监控的 URL 模式 |
钩子选项
| 选项 | 类型 | 用途 |
|---|---|---|
beforeSend | (SentryEvent, Hint) → SentryEvent? | 修改或丢弃错误事件。返回 null 即可丢弃 |
beforeSendTransaction | (SentryEvent) → SentryEvent? | 修改或丢弃事务事件 |
beforeBreadcrumb | (Breadcrumb, Hint) → Breadcrumb? | 存储前处理面包屑 |
beforeSendLog | (SentryLog) → SentryLog? | 发送前筛选结构化日志 |
环境变量
在构建时通过 --dart-define 传入:
| 变量 | 用途 | 备注 |
|---|---|---|
SENTRY_DSN | 数据源名称 | 回退到 options.dsn |
SENTRY_ENVIRONMENT | 部署环境 | 回退到 options.environment |
SENTRY_RELEASE | 发布标识符 | 回退到 options.release |
SENTRY_DIST | 构建分发标识 | 回退到 options.dist |
SENTRY_AUTH_TOKEN | 上传调试符号 | 切勿嵌入应用中——仅供构建工具使用 |
SENTRY_ORG | 组织标识 | 由 sentry_dart_plugin 使用 |
SENTRY_PROJECT | 项目标识 | 由 sentry_dart_plugin 使用 |
用法:
flutter build apk --release \
--dart-define=SENTRY_DSN=https://[email protected]/123 \
--dart-define=SENTRY_ENVIRONMENT=production
然后在代码中:
options.dsn = const String.fromEnvironment('SENTRY_DSN');
options.environment = const String.fromEnvironment('SENTRY_ENVIRONMENT', defaultValue: 'development');
生产环境设置
发布前降低采样率并强化配置:
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())),
);
}
默认自动启用的集成
调用 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 发布版本 |
验证
完成设置后,测试 Sentry 是否正在接收事件:
// 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'),
)
查看 Sentry 控制台:
- 问题 → 测试错误应在几秒内出现
- 追踪 → 查找包含子跨度的导航事务
- 回放 → 应用交互后可查看会话录制(仅限 iOS/Android)
- 日志 → 如果
enableLogs: true,则会显示结构化日志条目
⚠️ 调试模式下的平台限制:
- 原生崩溃、会话回放、卡顿/冻结帧以及应用启动指标只有在 iOS/Android 的发布构建中才能完全生效
- 运行
flutter run --release,或使用真实设备/模拟器测试原生功能- 调试模式使用带 JIT 编译的 Dart VM——部分原生集成的行为会有所不同
第 4 阶段:交叉链接
完成 Flutter 设置后,检查后端是否缺少 Sentry 监控:
# 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
如果检测到后端但未配置 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 传递追踪上下文:
options.tracePropagationTargets = ['api.myapp.com', 'localhost'];
options.propagateTraceparent = true; // also send W3C traceparent header
这样即可在 Sentry 瀑布视图中将移动端事务关联到后端追踪。
故障排除
| 问题 | 解决方案 |
|---|---|
| Sentry 中未显示事件 | 设置 options.debug = true——SDK 会将日志输出到 Flutter 控制台;确认 DSN 正确 |
SentryFlutter.init 抛出异常 | 确保 main() 是 async,并且对 SentryFlutter.init(...) 使用 await |
| 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 |
测试中出现 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) |