How to refresh firebase token on Flutter?

7,426

Solution 1

No, FCM token doesn't refresh every 3600 seconds. It only refreshes when :

  1. When user Uninstall/Reinstall the app or Clears App Data
  2. You manually delete FCM Instance using FirebaseMessaging().deleteInstanceID()

You can listen to token refresh stream using:

FirebaseMessaging().onTokenRefresh.listen((newToken) {
   // Save newToken
});

Hope it helps

Solution 2

You can use firebaseMessaging.onTokenRefresh to get a stream which receives an event each time a new token is received.

Solution 3

Here is an example of subscribing to the firebaseMessaging.onTokenRefresh stream and updating the token if the token has changed:

FirebaseMessaging().onTokenRefresh.listen((token) async {
  final prefs = await SharedPreferences.getInstance();
  final String firebaseTokenPrefKey = 'firebaseToken';
  final String currentToken = prefs.getString(firebaseTokenPrefKey);
  if (currentToken != token) {
    print('token refresh: ' + token);
    // add code here to do something with the updated token
    await prefs.setString(firebaseTokenPrefKey, token);
  }
});
Share:
7,426
Notheros
Author by

Notheros

Updated on December 06, 2022

Comments

  • Notheros
    Notheros over 1 year

    I have a Flutter app that uses Firebase messaging to delivery notifications. This is the base code, it does nothing special, besides saving the token on my DB.

     FirebaseMessaging _firebaseMessaging = new FirebaseMessaging();
    
     _firebaseMessaging.configure(
      onMessage: (Map<String, dynamic> message) {
    
      },
      onResume: (Map<String, dynamic> message) {
    
      },
      onLaunch: (Map<String, dynamic> message) {
    
      },
    );
    
    
    _firebaseMessaging.getToken().then((token) {
      saveToken(token);
    });
    

    Do I have to implement some kind of background service to keep saving the new token on my DB everytime it gets refreshed? I remember using onTokenRefresh() on Android(JAVA) to do this, but I found nothing about it in Flutter (DART).

    I read somewhere that the token gets refreshed every 3600 seconds. I wonder if this is true.