initialize static method

Future<FirebaseApp> initialize()

Implementation

static Future<FirebaseApp> initialize() async {
  if (_app != null) return _app!;

  FirebaseOptions options;
  final config = FirebaseConfig();

  if (Platform.isAndroid) {
    final androidOpts = config.getAndroidOptions();
    options = FirebaseOptions(
      apiKey: androidOpts['apiKey']!,
      appId: androidOpts['appId']!,
      messagingSenderId: androidOpts['messagingSenderId']!,
      projectId: androidOpts['projectId']!,
      storageBucket: androidOpts['storageBucket']!,
    );
  } else if (Platform.isIOS) {
    final iosOpts = config.getIOSOptions();
    options = FirebaseOptions(
      apiKey: iosOpts['apiKey']!,
      appId: iosOpts['appId']!,
      messagingSenderId: iosOpts['messagingSenderId']!,
      projectId: iosOpts['projectId']!,
      storageBucket: iosOpts['storageBucket']!,
      iosBundleId: iosOpts['iosBundleId']!,
    );
  } else {
    throw UnsupportedError("Unsupported platform for Firebase initialization");
  }

  // Initialize a dedicated, named FirebaseApp for the plugin
  try {
    _app = await Firebase.initializeApp(name: _appName, options: options);
  } on FirebaseException catch (e) {
    // If app with the same name already exists, return existing instance
    if (e.code == 'duplicate-app') {
      _app = Firebase.app(_appName);
    } else {
      rethrow;
    }
  }

  // Also ensure a DEFAULT app exists to satisfy libraries that implicitly
  // access Firebase.app() without specifying an app instance.
  try {
    // If this succeeds, a default app already exists and nothing to do
    Firebase.app();
  } on FirebaseException catch (e) {
    if (e.code == 'no-app') {
      // Create default app with the same options
      await Firebase.initializeApp(options: options);
    } else {
      rethrow;
    }
  }

  return _app!;
}