Flutter Firebase Push and Token Handling in easy way

Flutter Firebase Push and Token Handling in easy way

No more hard way, let's make firebase push notification and token handling make easy.

We will need this three packages to get start with our journey, just add to your dependency in pubspec.yml in flutter project,

firebase_core: ^2.5.0
firebase_messaging: ^14.2.2
flutter_local_notifications: ^13.0.0

Then create another dart file, where you will write your all the controlling stuffs for firebase push and token controlling.

First let's create a function where you will able to generate token and store it on the shared_preference.

void initiateToken([Function(String)? token = null]) {
  final fcmToken = FirebaseMessaging.instance.getToken();
  fcmToken.then((value) {
    print("FCM_TOKEN____________:   $value");
    if(token!=null){
      token(value!);
    }
    storeToken(value!);
    FirebaseMessaging.instance.onTokenRefresh.listen((value) {
      storeToken(value);
      print("TOKEN_REFRESH_SUCCEED_WITH_TOKEN__________${value}");
    }).onError((err) {
      print("TOKEN_REFRESH_FAILED_WITH_ERROR__________${err.toString()}");
    });
  });
}

void storeToken(String token) {
  StoragePref storagePref = StoragePref();
  storagePref.setString(FCM_TOKEN, token);
}

Now you have already generated and stored your valuable token from firebase. Now let's create and show a push notification to the user. You will need a data class for your push notification,

class PushNotification {
  PushNotification({
    this.title,
    this.body,
  });
  String? title;
  String? body;
}
void registerNotification(Function(PushNotification) initiated) async {
  // 1. Initialize the Firebase app
  await Firebase.initializeApp();

  // 2. Instantiate Firebase Messaging
  _messaging = FirebaseMessaging.instance;

  // 3. On iOS, this helps to take the user permissions
  NotificationSettings settings = await _messaging.requestPermission(
    alert: true,
    badge: true,
    provisional: false,
    sound: true,
  );

  if (settings.authorizationStatus == AuthorizationStatus.authorized) {
    print('User granted permission');

    // For handling the received notifications
    FirebaseMessaging.onMessage.listen((RemoteMessage message) {
      // Parse the message received
      PushNotification notification = PushNotification(
        title: message.notification?.title,
        body: message.notification?.body,
      );
      notificationInfo = notification;
      initiated(notificationInfo);
    });
  } else {
    print('User declined or has not accepted permission');
  }
}

But there is a problem, you cannot get push notifications in the background. To solve this problem let's create a simple function and call it in registerNotification function.

Future _firebaseMessagingBackgroundHandler(RemoteMessage message) async {
  print("Handling a background message: ${message.messageId}");
}

Now call this function from your splash or wherever you want to get started with push notification and firebase token.

initiateToken();
registerNotification((value)->{
   //use the push valuews
})

Thank you very much. Feel free to let me know how you have implemented and thus it works for you or not.