How to send Firebase notifications from Spring Boot to Flutter App?

How to send Firebase notifications from Spring Boot to Flutter App?

Using FCM, you can notify a client app that new email or other data is available to sync. You can transfer a payload of up to 4000 bytes to a client.

ยท

2 min read

Table of contents

No heading

No headings in the article.

Hello everyone, if you're developing an application where you want to send notifications from the backend to any platform android, ios, or web then this is the right article for you ๐Ÿ˜

Prerequisite:

  • Setup a Spring Boot project with at least these dependencies Spring Web, Spring Boot DevTools, Lombok
  • Create an account on the Firebase console firebase
  • Configure the Firebase in your Flutter project refer

Let's begin...

Implementation:

Step1: Download the Private key from Firebase Service Account

  • Project overview > Project Setting > Service Account

oopop.jpg

Step2: Add the Private key inside the Resource folder

kjkj.jpg

Step3: Add the Firebase dependency in pox.xml

<dependency>
            <groupId>com.google.firebase</groupId>
            <artifactId>firebase-admin</artifactId>
            <version>7.0.0</version>
</dependency>

Step4: Register the Bean with IOC to use FirebaseMessaging Object

@Configuration
public class FcmConfiguration {

    @Bean
    FirebaseMessaging firebaseMessaging()throws IOException {
    GoogleCredentials googleCredentials =GoogleCredentials.fromStream(new ClassPathResource("----your service account private key path------").getInputStream());
    FirebaseOptions firebaseOptions =FirebaseOptions.builder().setCredentials(googleCredentials).build();
    FirebaseApp app = FirebaseApp.initializeApp(firebaseOptions);
    return FirebaseMessaging.getInstance(app);
    }

}

Step5: Implement the Service class ( As per your requirement )

@Service
public class FcmService {

    @Autowired
    FirebaseMessaging firebaseMessaging;
    public String sendNotificationToSpecificDevice(MessageDTO note, String token) throws FirebaseMessagingException {
        Notification notification= Notification
                .builder()
                .setTitle(note.getSubject())
                .setBody(note.getContent())
                .setImage(note.getImage())
                .build();
        Message message = Message
        .builder()
                .setToken(token)
                .setNotification(notification)
                .putAllData(note.getData())
                .build();
        return firebaseMessaging.send(message);
    }
    public BatchResponse sendNotificationToMultipleDevices(MessageDTO note, List<String> tokens) throws FirebaseMessagingException {

        Notification notification= Notification
                .builder()
                .setTitle(note.getSubject())
                .setBody(note.getContent())
                .setImage(note.getImage())
                .build();

        MulticastMessage message = MulticastMessage
                .builder()
                .addAllTokens(tokens)
                .setNotification(notification)
                .putAllData(note.getData())
                .build();
        return firebaseMessaging.sendMulticast(message);
    }
    public void subscribeToTopic(List<String> tokens, String topic) throws FirebaseMessagingException {
        firebaseMessaging.subscribeToTopic(tokens,topic);
    }
    public void unSubscribeToTopic(List<String> tokens, String topic) throws FirebaseMessagingException {
        firebaseMessaging.subscribeToTopic(tokens,topic);
    }
    public String sendNotificationToTopic(MessageDTO note, String topic) throws  FirebaseMessagingException{
        Notification notification= Notification
                .builder()
                .setTitle(note.getSubject())
                .setBody(note.getContent())
                .setImage(note.getImage())
                .build();
        Message message = Message
                .builder()
                .setTopic(topic)
                .setNotification(notification)
                .putAllData(note.getData())
                .build();
        return firebaseMessaging.send(message);
    }
}

Step6: โค๏ธ Horray!!! Let's do the Testing

  • Get the token from the front-end (android, ios, web) using the firebase instance and send it to the backend API.

How to set up firebase in the flutter app?

  • All you need to do is set up the firebase at your front and send the token from there to the backend API. Note-

Example- Flutter Front End

class MyHomePage extends StatefulWidget {
  const MyHomePage({Key? key}) : super(key: key);

  @override
  State<MyHomePage> createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {


 // this method will give you the token
 Future<void> _getToken()async{
   final FirebaseMessaging _fcm= FirebaseMessaging.instance; 
   final deviceToken=await _fcm.getToken(); 
   log("token = "+deviceToken.toString());
 }

  @override
  Widget build(BuildContext context) {
    _getToken();
    return  Scaffold(
      appBar: AppBar(title: const Text("FCM")),
      body: const Center(
        child: Text("Flutter Fire"),
      ),
    );
  }
}

lllllllll.PNG

s.PNG

Reference

Github url https://github.com/abhishek-900/fcm-spring-boot

Official Doc https://firebase.google.com/docs/cloud-messaging

Thank you !!

Did you find this article valuable?

Support Abhishek's Blog by becoming a sponsor. Any amount is appreciated!

ย