How to get the device token in flutter

11.9k Views Asked by At

I'm trying to get the device token, for this i'm using FirebaseMessaging. here is my code to get the token.

@override
  void initState()  {
 FirebaseMessaging? _firebaseMessaging;
 _firebaseMessaging?.getToken().then((token){
      print("token is $token");
});
}


but it print nothing. Please help how to do this.

2

There are 2 best solutions below

0
Robert Sandberg On BEST ANSWER

You have to create the FirebaseMessaging instance. Change to:

@override
void initState() {
  FirebaseMessaging _firebaseMessaging = FirebaseMessaging.instance; // Change here
  _firebaseMessaging.getToken().then((token){
    print("token is $token");
  });
}
0
Nafees On

if you want to save token into firestore

final FirebaseMessaging _messaging = FirebaseMessaging.instance;
late String currentToken;
String userId = FirebaseAuth.instance.currentUser!.uid;
@override
void initState() {
_messaging.getToken().then((value) {
  print(value);
  if (mounted)
    setState(() {
      currentToken = value!;
    });
 FirebaseFirestore.instance
      .collection('pushtokens')
      .doc(userId)
      .set({'token': value!, 'createdAt': DateTime.now()});
 });