getFCMToken function

Future<String?> getFCMToken()

Retrieves the Firebase Cloud Messaging (FCM) token for the current device.

This function checks if the application is running on a web platform or a non-mobile platform (neither Android nor iOS). If it is, it returns null as FCM tokens are primarily for mobile push notifications. Otherwise, it attempts to get the FCM token using FirebaseMessaging.instance.getToken().

Returns a Future<String?> which resolves to the FCM token if successful, or null if an error occurs, the platform is web, or the platform is not Android/iOS.

Implementation

Future<String?> getFCMToken() async {
  if (kIsWeb) {
    // Skip for web
    return null;
  }

  if (!Platform.isAndroid && !Platform.isIOS) {
    // Only for mobile platforms
    return null;
  }

  try {
    final messaging = FirebaseMessaging.instance;
    final token = await messaging.getToken();
    return token;
  } catch (e) {
    print('Error getting FCM token: $e');
    return null;
  }
}