Flutter崩溃报告插件firebase_crashlytics的使用

发布于 1周前 作者 caililin 来自 Flutter

Flutter崩溃报告插件firebase_crashlytics的使用

Firebase Crashlytics for Flutter

pub package

Flutter的一个插件,用于使用Firebase Crashlytics API。要了解更多关于Crashlytics的信息,请访问Firebase网站

开始使用

为了开始使用Flutter的Crashlytics,请参考官方文档

使用方法

要使用此插件,请参阅Crashlytics Usage文档

问题和反馈

请在我们的issue tracker中提交与FlutterFire相关的问题、错误或功能请求。

非特定于FlutterFire的插件问题可以在Flutter issue tracker中提交。

如果您想为此插件贡献更改,请查看我们的贡献指南,并打开一个pull request

示例代码

以下是一个完整的示例demo,演示了如何使用firebase_crashlytics插件:

// ignore_for_file: require_trailing_commas
import 'dart:async';
import 'dart:io';

import 'package:firebase_core/firebase_core.dart';
import 'package:firebase_crashlytics/firebase_crashlytics.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';

import 'firebase_options.dart';

// Toggle this to cause an async error to be thrown during initialization
// and to test that runZonedGuarded() catches the error
const _kShouldTestAsyncErrorOnInit = false;

// Toggle this for testing Crashlytics in your app locally.
const _kTestingCrashlytics = true;

Future<void> main() async {
  WidgetsFlutterBinding.ensureInitialized();
  await Firebase.initializeApp(
    options: DefaultFirebaseOptions.currentPlatform,
  );
  const fatalError = true;
  // Non-async exceptions
  FlutterError.onError = (errorDetails) {
    if (fatalError) {
      // If you want to record a "fatal" exception
      FirebaseCrashlytics.instance.recordFlutterFatalError(errorDetails);
      // ignore: dead_code
    } else {
      // If you want to record a "non-fatal" exception
      FirebaseCrashlytics.instance.recordFlutterError(errorDetails);
    }
  };
  // Async exceptions
  PlatformDispatcher.instance.onError = (error, stack) {
    if (fatalError) {
      // If you want to record a "fatal" exception
      FirebaseCrashlytics.instance.recordError(error, stack, fatal: true);
      // ignore: dead_code
    } else {
      // If you want to record a "non-fatal" exception
      FirebaseCrashlytics.instance.recordError(error, stack);
    }
    return true;
  };
  runApp(MyApp());
}

class MyApp extends StatefulWidget {
  MyApp({Key? key}) : super(key: key);
  @override
  _MyAppState createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
  late Future<void> _initializeFlutterFireFuture;

  Future<void> _testAsyncErrorOnInit() async {
    Future<void>.delayed(const Duration(seconds: 2), () {
      final List<int> list = <int>[];
      print(list[100]);
    });
  }

  // Define an async function to initialize FlutterFire
  Future<void> _initializeFlutterFire() async {
    if (_kTestingCrashlytics) {
      // Force enable crashlytics collection enabled if we're testing it.
      await FirebaseCrashlytics.instance.setCrashlyticsCollectionEnabled(true);
    } else {
      // Else only enable it in non-debug builds.
      // You could additionally extend this to allow users to opt-in.
      await FirebaseCrashlytics.instance
          .setCrashlyticsCollectionEnabled(!kDebugMode);
    }

    if (_kShouldTestAsyncErrorOnInit) {
      await _testAsyncErrorOnInit();
    }
  }

  @override
  void initState() {
    super.initState();
    _initializeFlutterFireFuture = _initializeFlutterFire();
  }

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: const Text('Crashlytics example app'),
        ),
        body: FutureBuilder(
          future: _initializeFlutterFireFuture,
          builder: (context, snapshot) {
            switch (snapshot.connectionState) {
              case ConnectionState.done:
                if (snapshot.hasError) {
                  return Center(
                    child: Text('Error: ${snapshot.error}'),
                  );
                }
                return Center(
                  child: Column(
                    children: <Widget>[
                      ElevatedButton(
                        onPressed: () {
                          FirebaseCrashlytics.instance
                              .setCustomKey('example', 'flutterfire');
                          ScaffoldMessenger.of(context)
                              .showSnackBar(const SnackBar(
                            content: Text(
                                'Custom Key "example: flutterfire" has been set \n'
                                'Key will appear in Firebase Console once an error has been reported.'),
                            duration: Duration(seconds: 5),
                          ));
                        },
                        child: const Text('Set Custom Key'),
                      ),
                      ElevatedButton(
                        onPressed: () {
                          FirebaseCrashlytics.instance.log('This is a log example');
                          ScaffoldMessenger.of(context)
                              .showSnackBar(const SnackBar(
                            content: Text(
                                'The message "This is a log example" has been logged \n'
                                'Message will appear in Firebase Console once an error has been reported.'),
                            duration: Duration(seconds: 5),
                          ));
                        },
                        child: const Text('Log Message'),
                      ),
                      ElevatedButton(
                        onPressed: () async {
                          ScaffoldMessenger.of(context)
                              .showSnackBar(const SnackBar(
                            content: Text('App will crash in 5 seconds \n'
                                'Please reopen to send data to Crashlytics'),
                            duration: Duration(seconds: 5),
                          ));

                          // Delay crash for 5 seconds
                          await Future.delayed(const Duration(seconds: 5));

                          // Use FirebaseCrashlytics to throw an error. Use this for
                          // confirmation that errors are being correctly reported.
                          FirebaseCrashlytics.instance.crash();
                        },
                        child: const Text('Crash App'),
                      ),
                      ElevatedButton(
                        onPressed: () {
                          ScaffoldMessenger.of(context)
                              .showSnackBar(const SnackBar(
                            content: Text(
                                'Thrown error has been caught and sent to Crashlytics.'),
                            duration: Duration(seconds: 5),
                          ));

                          // Example of thrown error, it will be caught and sent to
                          // Crashlytics.
                          throw StateError('Uncaught error thrown by app');
                        },
                        child: const Text('Throw Error'),
                      ),
                      ElevatedButton(
                        onPressed: () {
                          ScaffoldMessenger.of(context)
                              .showSnackBar(const SnackBar(
                            content: Text(
                                'Uncaught Exception that is handled by second parameter of runZonedGuarded.'),
                            duration: Duration(seconds: 5),
                          ));

                          // Example of an exception that does not get caught
                          // by `FlutterError.onError` but is caught by
                          // `runZonedGuarded`.
                          runZonedGuarded(() {
                            Future<void>.delayed(const Duration(seconds: 2),
                                () {
                              final List<int> list = <int>[];
                              print(list[100]);
                            });
                          }, FirebaseCrashlytics.instance.recordError);
                        },
                        child: const Text('Async Out of Bounds'),
                      ),
                      ElevatedButton(
                        onPressed: () async {
                          try {
                            ScaffoldMessenger.of(context)
                                .showSnackBar(const SnackBar(
                              content: Text('Recorded Fatal Error'),
                              duration: Duration(seconds: 5),
                            ));
                            throw Error();
                          } catch (e, s) {
                            // "reason" will append the word "thrown" in the
                            // Crashlytics console.
                            await FirebaseCrashlytics.instance.recordError(e, s,
                                reason: 'as an example of fatal error',
                                fatal: true);
                          }
                        },
                        child: const Text('Record Fatal Error'),
                      ),
                      ElevatedButton(
                        onPressed: () async {
                          try {
                            ScaffoldMessenger.of(context)
                                .showSnackBar(const SnackBar(
                              content: Text('Recorded Non-Fatal Error'),
                              duration: Duration(seconds: 5),
                            ));
                            throw Error();
                          } catch (e, s) {
                            // "reason" will append the word "thrown" in the
                            // Crashlytics console.
                            await FirebaseCrashlytics.instance.recordError(e, s,
                                reason: 'as an example of non-fatal error');
                          }
                        },
                        child: const Text('Record Non-Fatal Error'),
                      ),
                    ],
                  ),
                );
              default:
                return const Center(child: Text('Loading'));
            }
          },
        ),
      ),
    );
  }
}

这个示例展示了如何集成和使用firebase_crashlytics插件来记录Flutter应用程序中的崩溃和错误。它包括设置自定义键、记录日志、抛出异常以及捕获同步和异步错误的功能。通过这些按钮,您可以测试不同类型的错误处理,并确保它们能够正确地发送到Firebase Crashlytics控制台。


更多关于Flutter崩溃报告插件firebase_crashlytics的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html

1 回复

更多关于Flutter崩溃报告插件firebase_crashlytics的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html


当然,下面是一个关于如何在Flutter项目中使用firebase_crashlytics插件来捕获和处理崩溃报告的详细代码案例。

1. 添加依赖

首先,你需要在pubspec.yaml文件中添加firebase_crashlytics依赖:

dependencies:
  flutter:
    sdk: flutter
  firebase_core: ^1.10.0  # 确保你也添加了firebase_core
  firebase_crashlytics: ^2.4.0  # 使用最新版本

然后运行flutter pub get来安装这些依赖。

2. 配置Firebase

在Firebase控制台中为你的应用创建一个项目,并获取google-services.json文件(对于Android)和GoogleService-Info.plist文件(对于iOS)。将这些文件分别放在android/app/ios/Runner/目录下。

3. 初始化Firebase

在你的Flutter应用的main.dart文件中,初始化Firebase和Crashlytics:

import 'package:flutter/material.dart';
import 'package:firebase_core/firebase_core.dart';
import 'package:firebase_crashlytics/firebase_crashlytics.dart';

void main() async {
  WidgetsFlutterBinding.ensureInitialized();
  await Firebase.initializeApp();

  // 启用Crashlytics
  await FirebaseCrashlytics.instance.setCrashlyticsCollectionEnabled(true);

  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: Text('Firebase Crashlytics Demo'),
        ),
        body: Center(
          child: CrashButton(),
        ),
      ),
    );
  }
}

class CrashButton extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return ElevatedButton(
      onPressed: () {
        // 强制崩溃示例
        crashApp();
      },
      child: Text('Crash App'),
    );
  }

  void crashApp() {
    // 使用Crashlytics记录自定义非致命异常
    FirebaseCrashlytics.instance.recordError(
      Exception('This is a custom non-fatal exception'),
      StackTrace.fromString('This is the stack trace'),
    );

    // 强制应用崩溃
    // 注意:下面的代码会导致应用崩溃,仅在调试和开发中使用
    // 在生产环境中,你应该避免直接调用这样的代码
    int.parse('not_a_number');  // 这将抛出FormatException并导致应用崩溃
  }
}

4. 捕获未处理的异常

为了确保所有未处理的异常都被捕获并发送到Firebase Crashlytics,你可以使用FlutterError.onError

void main() async {
  WidgetsFlutterBinding.ensureInitialized();
  FlutterError.onError = (FlutterErrorDetails details) {
    if (kReleaseMode) {
      // 在发布模式下,将错误发送到Crashlytics
      FirebaseCrashlytics.instance.recordFlutterError(details);
    } else {
      // 在调试模式下,打印错误到控制台(或进行其他处理)
      FlutterError.dumpErrorToConsole(details);
    }
    // 确保继续传递错误以进行默认的报告处理
    Zone.current.handleUncaughtException(details.exception, details.stack);
  };

  await Firebase.initializeApp();
  await FirebaseCrashlytics.instance.setCrashlyticsCollectionEnabled(true);

  runApp(MyApp());
}

5. 测试崩溃报告

运行你的应用,并点击“Crash App”按钮。应用将会崩溃,并且崩溃报告会被发送到Firebase Crashlytics。你可以在Firebase控制台中查看这些报告,并分析崩溃的原因和堆栈跟踪。

总结

通过以上步骤,你已经成功在Flutter项目中集成了Firebase Crashlytics,并能够捕获和处理崩溃报告。这对于提高应用的稳定性和用户体验至关重要。

回到顶部