Search code examples
flutterfirebasedartcrashlytics

How can I deal with crash correctly while using firebase in flutter?


In my flutter project, I just using firebase like this:

//main.dart
Future<void> main() async {
  WidgetsFlutterBinding.ensureInitialized();
  await Firebase.initializeApp(
    options: DefaultFirebaseOptions.currentPlatform,
  );

  FlutterError.onError = FirebaseCrashlytics.instance.recordFlutterFatalError;
  PlatformDispatcher.instance.onError = (error, stack) {
    FirebaseCrashlytics.instance.recordError(error, stack, fatal: true);
    return true;
  };

  runApp(MyApp());
}

It looks like firebase can only catch crashes when using like

 final result = await someThrowErrorFunctions;

But if I deal with any functions like:

try {
  final result = await someThrowErrorFunctions;     
} catch (e) {
  print('error:$e');
}

The app will not crash but I cannot catch the error in firebase, and I won't know there is an error, right?

What if I wanna don't crash, and at the same time I could catch the error with firebase, is it possible? And what is the correct usage?

Any help will be appreciate, thanks~


Solution

  • I suggest reviewing the documentation on reporting caught exceptions, which is what you're trying to here. It will look something like this:

    try {
      final result = await someThrowErrorFunctions;     
    } catch (e) {
      await FirebaseCrashlytics.instance.recordFlutterError(e);
    }