简体   繁体   English

正确使用 Firebase 消息和 Flutter 的 onTokenRefresh() 方法

[英]Correct way to use onTokenRefresh() of Firebase Messaging and Flutter

I'm building a Flutter application and want to send Firebase Cloud Messaging notifications specifically to different users with their respective Firebase Token.我正在构建一个 Flutter 应用程序,并希望使用各自的 Firebase 令牌专门向不同的用户发送 Firebase 云消息通知。 The problem is when the app is reinstall or after some period of time, the Firebase Token is regenerated.问题是在重新安装应用程序或一段时间后,重新生成 Firebase 令牌。

How can I use the onTokenRefresh() method to notice the change of token continuously (even when the app is not opened) and send the new token to my backend server?如何使用onTokenRefresh()方法持续注意到令牌的变化(即使应用程序未打开)并将新令牌发送到我的后端服务器?

Thank you.谢谢你。

The code should look like this:代码应如下所示:


Future<void> main() async {
  WidgetsFlutterBinding.ensureInitialized();

  await Firebase.initializeApp();
  FirebaseMessaging.instance.onTokenRefresh.listen((String token) {
    print("New token: $token");

  // sync token to server
  });

  String token = await FirebaseMessaging.instance.getToken();
  // sync token to server
  print("Token: $token");
  //runApp(MyApp());
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM