The issue with your code of simulating the error is that you have to await for the crash to happen - like this:
try {
await crashFunction();
} catch (error) {
prefs.writeBool(key: "crash", value: true);
}
In this case, the catch block will work.
FirebaseCrashlytics.instance.crash();
triggers the native app terminating crash, so I assume that is why catch
did not work in this case - it cannot catch such kinds of crashes. You should use try catch
to handle Dart/Flutter exceptions but not the Native crashes - it will not work like that.
Regarding your question - you cannot log anything before the crash - because you don't know when the crash will happen - but you sure can do it after in catch block(if the crash is not app terminating(but even in that case, there are ways to perform some logic))
The solution to that may be a wide logging system - so you would log everything needed to you, disregarding the crash occurrence. It may look too verbose but it is the only possible way to log something before the crash - log everything and everywhere.
If you want more info in the catch block, you can use another override of catch that looks like this:
try{
...
} catch (error, stacktrace){
//save to sharedprefs
}
In this case, you can store the complete stacktrace instead of just the error description.
Also you can catch specific errors with the help of :
try{
} on SomeException catch(error){
}
This override will catch only instances of SomeException
and all the other ones will be thrown.
If you want to catch an app terminating error - I don't think there is a way in a clean flutter - but there is for sure a way to do that from the native platform as described here for Android.
Hope it helps