linkWithGamesServices method

Future<UserCredential> linkWithGamesServices({
  1. bool forceSignInWithGameServiceIfCredentialAlreadyUsed = false,
})

Links the current Firebase user with Play Games (Android) or Game Center (iOS).

This method fetches the appropriate game service credentials (either Play Games on Android or Game Center on iOS) and attempts to link them with the current Firebase user account.

forceSignInWithGameServiceIfCredentialAlreadyUsed indicates whether to force a sign-in with game services if the credentials are already linked with another account. If set to true, the user is signed out and signed in again using game services.

Throws:

  • UnimplementedError for unsupported platforms (non-Android, non-iOS).
  • FirebaseAuthGamesServicesException if authentication with game services fails.
  • FirebaseAuthException if linking with Firebase fails (e.g., invalid credentials, network issues).

Implementation

Future<UserCredential> linkWithGamesServices(
    {bool forceSignInWithGameServiceIfCredentialAlreadyUsed = false}) async {
  try {
    // Handle linking on Android (Play Games).
    if (Platform.isAndroid) {
      final playGamesCredential =
          await GameServicesCredentialsUtils.getPlayGamesCredential();
      return await linkWithCredential(playGamesCredential);
    }

    // Handle linking on iOS (Game Center).
    if (Platform.isIOS) {
      final gameCenterCredential =
          await GameServicesCredentialsUtils.getGameCenterCredential();
      return await linkWithCredential(gameCenterCredential);
    }

    // Unsupported platform error.
    throw UnimplementedError(
        'This platform is not supported. Only Android and iOS are supported.');
  } on FirebaseAuthException catch (e) {
    // Handle the case where credentials are already linked with another account.
    if (forceSignInWithGameServiceIfCredentialAlreadyUsed &&
        e.code == 'credential-already-in-use') {
      await FirebaseAuth.instance.signOut();
      return FirebaseAuth.instance.signInWithGamesServices();
    }
    rethrow; // Re-throw the exception if not handled.
  }
}