DEV Community

Cover image for Notifications in flutter
Akash Pattnaik
Akash Pattnaik

Posted on

Notifications in flutter

Hello fam 👋!

This tutorial shows the easiest way to implement push notifications in flutter. Stick till then end for a better grasp at the concept!

It's 2024 and still most of these docs are quite confusing. Awesome Notifications package has an extremely well documented docs but all in one page. This makes it look like shit!

Contents

  • Required Packages 📦
  • Initialization 🤩
  • Sending Notifications 📨
  • Setup Firebase 🔥
  • Sending Notifications 🛎️
  • Setup Notifications in background 🚀

Required Packages 📦

Initialization 🤩

In the main.dart file, under the main void, add the following codes -

import 'package:awesome_notifications/awesome_notifications.dart';
import 'package:firebase_messaging/firebase_messaging.dart';
import './firebase_options.dart';
import 'package:firebase_core/firebase_core.dart';
import 'package:flutter/material.dart';

void main() async {
  WidgetsFlutterBinding.ensureInitialized();
  await Firebase.initializeApp(
    options: DefaultFirebaseOptions.currentPlatform,
  );
  runApp(const App());
  await FirebaseMessaging.instance.setAutoInitEnabled(true); // Enables the notifications automatically!
  await FirebaseMessaging.instance.requestPermission(provisional: true); // Request the user for permissions of notifications
  await FirebaseMessaging.instance.getToken(); // The is used to get a token, specific for each user, generated by firebase
  await AwesomeNotifications().initialize(null, [
    NotificationChannel(
        channelKey: 'random_unique_key',
        channelName: 'A name visible to the user',
        channelDescription: 'Description',
    ),
  ]);
}
Enter fullscreen mode Exit fullscreen mode

This registers the channel along with the key with android system. Now you can use these channels, through the keys to send notifications to the users!

Sending Notifications 📨

Assuming that you have a basic knowledge of flutter (this tutorial isn't for you if you don't), use these codes inside the initState function of your homepage that is shown to the user after login!

import 'package:awesome_notifications/awesome_notifications.dart';
import 'package:firebase_messaging/firebase_messaging.dart';
import 'package:flutter/material.dart';

class HomePageState extends State<HomePage> {
  AwesomeNotifications notifications = AwesomeNotifications();
  @override
  void initState() {
    super.initState();
    FirebaseMessaging.onMessage.listen((RemoteMessage event) async {
      await notifications.createNotification(
        content: NotificationContent(
          id: 0, // Doesn't really matter that much
          channelKey: 'key', // The unique key that you registered at the start
          title: event.notification!.title!,
          body: event.notification!.body!,
          notificationLayout: NotificationLayout.BigPicture,
          bigPicture: event.notification!.android!.imageUrl,
        ),
        actionButtons: [
          NotificationActionButton(key: '_', label: 'Ok', autoDismissible: true),
        ],
      );
    });
  }
}
Enter fullscreen mode Exit fullscreen mode

Setup Firebase 🔥

From the above code you can clearly derive that Firebase is needed for this project. So go ahead and add it! Then, come the most crucial part!

Under engage section, goto messaging!

Messaging

Sending Notifications 🛎️

It's your first time, so click on create a new campaign! Fill it up like this.

Test Notification

Notification Display

This is how it will be shown on your device!

Setup Notifications in background 🚀

The above code only works if the app is open in the foreground and user is using it. It DOES NOT work if app is closed or even in background apps.

For that, there is a simple and quite an easy fix!

In the main.dart file, add this ->

Future<void> backgroundNotificationHandler(RemoteMessage event) async {
  await AwesomeNotifications().createNotification(
    content: NotificationContent(
      id: 0,
      channelKey: 'key',
      title: event.notification!.title!,
      body: event.notification!.body!,
      notificationLayout: NotificationLayout.BigPicture,
      bigPicture: event.notification!.android!.imageUrl,
    ),
    actionButtons: [
      NotificationActionButton(key: '_', label: 'Ok', autoDismissible: true),
    ],
  );
}

void main() {
    FirebaseMessaging.onBackgroundMessage(backgroundNotificationHandle);
}
Enter fullscreen mode Exit fullscreen mode

Top comments (1)

Collapse
 
newdev0 profile image
Devesh Pal • Edited

Detailed and insightful 🎊