init method
Initializes Firebase Analytics and Crashlytics error handling.
Implementation
@override
Future<void> init(
{Map? options, String? ensembleAppId, bool shouldAwait = false}) async {
_init(
options: options,
ensembleAppId: ensembleAppId,
shouldAwait: shouldAwait);
bool isFirebaseAppInitialized = false;
// PRIORITY: If we have a provided Firebase app from constructor, use it to initialize Analytics
if (_providedFirebaseApp != null) {
try {
_analytics = FirebaseAnalytics.instanceFor(app: _providedFirebaseApp);
isFirebaseAppInitialized = true;
// Setup crash reporting if available
try {
FlutterError.onError = _handleFlutterError;
// Handle errors outside of Flutter framework (like async errors)
PlatformDispatcher.instance.onError = (error, stack) {
FirebaseCrashlytics.instance.recordError(error, stack,
fatal: _shouldTreatAsyncErrorAsFatal(error));
return true;
};
} catch (e) {
print('Flutter: ⚠️ Firebase Crashlytics not available: $e');
}
return; // Success - exit early
} catch (e) {
print(
'Flutter: ❌ Failed to initialize Firebase Analytics with provided app: $e');
}
}
try {
isFirebaseAppInitialized =
Firebase.apps.any((app) => app.name == Firebase.app().name);
} catch (e) {
// Firebase flutter web implementation throws error of uninitialized project
// When project is not initialized which means we just catch the error and ignore it
}
if (!isFirebaseAppInitialized) {
try {
await Firebase.initializeApp(
// has to be the default app for the analytics to work on native apps
options: firebaseOptions,
);
} catch (e) {
print(
"Failed to initialize firebase app, make sure you either have the firebase options specified in the config file (required for web) "
"or have the right google file for the platform - google-services.json for android and GoogleService-Info.plist for iOS.");
rethrow;
}
} else {
FirebaseApp defaultApp = Firebase.app();
if (firebaseOptions != null &&
defaultApp.options.appId != firebaseOptions!.appId) {
throw ConfigError(
'The appId: ${firebaseOptions?.appId} specified in the Firebase configuration for ensembleapp with id: ${ensembleAppId ?? 'undefined'} is not the default firebase app. '
'And the firebase default app has already been initialized. Firebase analytics can only work with the default firebase app');
}
}
_analytics = FirebaseAnalytics.instance;
// Setup comprehensive error handling
FlutterError.onError = _handleFlutterError;
// Handle async errors that aren't caught by Flutter framework
PlatformDispatcher.instance.onError = (error, stack) {
FirebaseCrashlytics.instance.recordError(error, stack,
fatal: _shouldTreatAsyncErrorAsFatal(error));
return true;
};
}