addFirebaseToApp function

Future<void> addFirebaseToApp({
  1. required String firebaseProjectId,
  2. required String packageName,
  3. bool? skip,
})

Adds Firebase to a Flutter application using the FlutterFire CLI.

This function configures Firebase for the Android and iOS platforms of the Flutter application. It first checks the firebase.json file to see if the provided firebaseProjectId matches an existing configuration. If not, it prompts the user for confirmation to proceed.

It then activates the flutterfire_cli globally and runs the flutterfire configure command to integrate Firebase with the app.

firebaseProjectId The ID of the Firebase project to link with the app. packageName The package name (Android application ID and iOS bundle ID) of the app. skip If true, prompts for re-running configuration will be skipped.

Throws an Exception if firebase.json is not found or invalid, or if the flutterfire commands fail.

Implementation

Future<void> addFirebaseToApp({
  required String firebaseProjectId,
  required String packageName,
  bool? skip,
}) async {
  final firebaseJsonPath = clonifySettings.firebaseSettingsFilePath;

  try {
    // Step 1: Parse the firebase.json file
    logger.i('πŸ” Checking for firebase.json in the project root...');
    final firebaseJsonFile = File(firebaseJsonPath);
    if (!firebaseJsonFile.existsSync()) {
      logger.e('❌ No firebase.json file found in the project root.');
      logger.i('  Please run "firebase init" to add Firebase to your app.');
      return;
    }

    final firebaseJsonContent =
        jsonDecode(firebaseJsonFile.readAsStringSync()) as Map<String, dynamic>;

    // Step 2: Check if the project ID matches
    final flutterPlatforms = firebaseJsonContent['flutter']?['platforms'];
    if (flutterPlatforms == null) {
      logger.e('❌ No platforms found in firebase.json.');
      logger.i('  Please run "firebase init" to add Firebase to your app.');
      return;
    }

    bool projectIdMatches = false;

    for (final platform in flutterPlatforms.entries) {
      final platformData = platform.value as Map<String, dynamic>;
      if (platformData['default']?['projectId'] == firebaseProjectId) {
        projectIdMatches = true;
        logger.i(
          'βœ… Firebase project ID matches for platform: ${platform.key} (${platformData['default']?['projectId']})',
        );
      }
    }

    if (projectIdMatches) {
      if (skip == false) {
        final userChoice = prompt(
          'Firebase project ID matches the current configuration. Do you want to re-run the command anyway? (y/n):',
        );
        if (userChoice.toLowerCase() != 'y') {
          logger.i('>>| Skipping Firebase configuration...');
          return;
        }
      } else {
        logger.i(
          'βœ… Firebase project ID matches the current configuration.\n>>| Skipping Firebase configuration...',
        );
        return;
      }
    } else {
      logger.e(
        '❌ Firebase project ID does not match any configuration in firebase.json.',
      );
      if (skip == false) {
        final userChoice = prompt(
          'Do you want to proceed with Firebase configuration for project ID: $firebaseProjectId? (y/n):',
        );
        if (userChoice.toLowerCase() != 'y') {
          logger.i('πŸš€ Skipping Firebase configuration...');
          return;
        }
      } else {
        logger.i(
          '>>| Proceeding with Firebase configuration for project ID: $firebaseProjectId...',
        );
      }
    }

    // Step 3: Activate Flutterfire CLI
    logger.i('πŸ›  Activating Flutterfire CLI...');
    await runCommand('dart', [
      'pub',
      'global',
      'activate',
      'flutterfire_cli',
    ], successMessage: 'βœ… Flutterfire CLI activated successfully.');

    // Step 4: Add Firebase to Android and iOS
    logger.i('πŸ›  Adding Firebase to your Flutter app...');
    await runCommand(
      'flutterfire',
      [
        'configure',
        '--project',
        firebaseProjectId,
        '-y',
        '--platforms=android,ios',
        '-i',
        packageName,
        '-a',
        packageName,
      ],
      successMessage: 'βœ… Firebase added successfully to your Flutter app.',
    );

    logger.i("[!] Don't forget to upload the APNs key to Firebase Console [!]");
  } catch (e) {
    logger.e('❌ Error during Firebase setup: $e');
  }
}