Home > Net >  Why device token generated in every run of the flutter application?
Why device token generated in every run of the flutter application?

Time:02-04

I'm using firebase cloud messaging to send notifications to devices. The problem is that the device token regenrated and added to firestore with different id in every run of the application. I want it to be generated juste once for the first installation of the application. this is my code :

 Future init() async {


    _firebaseMessaging.getToken().then((token) {
      saveTokens(token);
    });
}

  Future<void> saveTokens(var token) async {
    try {
      await _firestore.collection('deviceTokens').add({
        'token': token,
      });
    } catch (e) {
      print(e);
    }
  }


this is how I call it in the main():

  await Firebase.initializeApp(options: DefaultFirebaseOptions.currentPlatform);

  await _msgService.init();

  // testFirestore();
  FirebaseMessaging.onBackgroundMessage(_messageHandler);

this is _messageHandler function:

Future<void> _messageHandler(RemoteMessage message) async {
  print(
      'background message ${message.notification!.body}   ${message.notification!.title}');
}

CodePudding user response:

Actually token only refresh on one of that cases:

  • The app deletes Instance ID
  • The app is restored on a new device
  • The user uninstalls/reinstall the app
  • The user clears app data.

So you need to check in your firebase collection if your token (getted on getToken()) is saved yet before add it. If it already exists in your database, don't save it.

For example:

Future<bool> doesTokenAlreadyExist(String token) async {
  final QuerySnapshot result = await Firestore.instance
    .collection('deviceTokens')
    .where('token', isEqualTo: token)
    .limit(1)
    .getDocuments();
  final List<DocumentSnapshot> documents = result.documents;
  return documents.length == 1;
}

CodePudding user response:

The registration token may change when:

  • The app is restored on a new device
  • The user uninstalls/reinstall the app
  • The user clears app data.

More :

  • Update from Play Store - Token remains same.
  • When close the application and reopen it - Token remains same.

I recommend you should record that token for the user every time your app launches. Then, you don't face any problems. (add function to init state of home page of your app)

  • Related