Notifications in flutter
Tags: flutter, beginners, tutorial, productivity
Published: 2024-02-12 16:33:09

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 📦
- [firebase_core](https://pub.dev/packages/firebase_core)
- [firebase_messaging](https://pub.dev/packages/firebase_messaging)
- [awesome_notifications](https://pub.dev/packages/awesome_notifications)

### Initialization 🤩

In the `main.dart` file, under the `main` void, add the following codes -
```dart
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',
    ),
  ]);
}
```

> 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**!

```dart
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),
        ],
      );
    });
  }
}
```

### 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](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ya0vprxehipk6xpkrsxy.png)

### Sending Notifications 🛎️

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

![Test Notification](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/7tmh7cetguqx9j6n8591.png)

![Notification Display](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/651o0lknyhl425xrib0w.png)

> 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 ->

```dart
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);
}
```