Aldy Yuan
Aldy Yuan

Reputation: 2045

Flutter FCM getToken() returns null

FCM getToken() always returns null on real devices, but is working just fine on emulator, I don't know what causes this. Here's how I use getToken():

FirebaseMessaging _firebaseMessaging = FirebaseMessaging();
String fcmToken = "";
await _firebaseMessaging.getToken().then((value) async {
  fcmToken = value;
  if (fcmToken != "") {
    await _userCollection.doc(user.id).set({
      'email': user.email,
      'name': user.name,
      'noHp': user.noHp,
      'alamat': user.alamat,
      "email_verification": user.emailVerification,
      "phone_verification": user.phoneVerification,
      "device_token": fcmToken,
    });
  }
  return;
});

The real device that I use is Android Marshmallow.

Upvotes: 4

Views: 9209

Answers (2)

Aviad
Aviad

Reputation: 71

There's a new way to access the token for those with the updated versions:

String token = await FirebaseMessaging.instance.getToken();

You'd be able to access the token only after you initialize Firebase & request permissions.

Upvotes: 0

Ketan P
Ketan P

Reputation: 4379

Below is the method for et Token :

final FirebaseMessaging _firebaseMessaging = FirebaseMessaging();

_firebaseMessaging.getToken().then((String token) {
   assert(token != null);
   saveToken(token);
});

I am saving token in pref for further use. you can modify it as per you requirement.

void saveToken(String token) async {
    var prefs = await SharedPreferences.getInstance();
    await prefs.setString(Constants.DeviceToken, token);
}

Feel free to comment if any issue. I am using in my current application.

For iOS you need to ask for permission.

    _firebaseMessaging.requestNotificationPermissions(
        const IosNotificationSettings(
            sound: true, badge: true, alert: true, provisional: true));
    _firebaseMessaging.onIosSettingsRegistered
        .listen((IosNotificationSettings settings) {
      print("Settings registered: $settings");
    });

Upvotes: 3

Related Questions