Getting to know Flutter: Easy notifications with MBMessages
Tags: flutter, beginners, dart, tutorial
Published: 2021-09-22 15:05:00

One of the most requested features when you develop an app are **Push Notifications**. Those messages are an awesome way to **engage** users with personalized content but may be a bit hard to implement "the good way". Here we want to show you how easy it is to implement on your Flutter application Push Notifications using the power of **MBurger** and the **MBMessages** library.

 

### Initialize MBurger and add MBMessages

If you haven't done it already check out our article about **Pull to Refresh** to know [how to create a new MBurger project](https://dev.to/theotherdevs/getting-to-know-flutter-pull-to-refresh-with-online-data-592i). In a few words you'll need to:

- Register for free on MBurger
- Create a new project
- Create an API Key

If you are unsure on how to do these steps refer [this guide](https://docs.mburger.cloud/api-docs-1/introduction/getting-started). Once you've done all of this you have to add MBMessages dependency to your project. Head over to [this page](https://pub.dev/packages/mbmessages) and add it as your dependency:

```dart
dependencies:
  mbmessages: ^2.0.1
```

First step completed, well done!

 

### Configure push notifications on MBurger

Next we'll configure push notifications on our app. Let's return on **MBurger** website and let's enable **Push Notifications** on settings. Here you can also enable integrations with other systems real easily.


![Alt Text](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/unpkz3r78rkaxa3g1zjz.png)
 
![Alt Text](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/s5v5pps74unzc90lg9jm.png)


By enabling it a new menu called "**Engagement**" on the left will appear. Here you'll have to configure **MBurger** to use the **MPush** subsystem in order to send Push Notifications.

Click on it and then on "Settings".

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/u5wop1u5o3dxkmga4u5t.png)

In this screen you'll see a generated token and two boxes, one for **Android** and one for **iOS**. You'll need to compile those boxes by linking your **Firebase** and **AppStore Connect** apps.

For iOS you'll need to create an **APNS API Key** ([click here](https://docs.mpush.cloud/ios-sdk/add-push-notification-to-your-app) if you are not sure on how to achieve it), you'll also need to add your **Apple Team ID** and **App Bundle**. Once you have added all click on "Update". Be aware for the "Production" checkbox, if you're trying push notification on a development device keep this checkbox to off and enable it only one you'll go live.

Then you have to modify the `AppDelegate `class of your application, open `AppDelegate.swift` file and add this line in the didFinishLaunchingWithOptions function.

```dart
UNUserNotificationCenter.current().delegate = self
```

The app delegate should look like this.

```dart
import UIKit
import Flutter

@UIApplicationMain
@objc class AppDelegate: FlutterAppDelegate {
  override func application(
    _ application: UIApplication,
    didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?
  ) -> Bool {
    UNUserNotificationCenter.current().delegate = self
    GeneratedPluginRegistrant.register(with: self)
    return super.application(application, didFinishLaunchingWithOptions: launchOptions)
  }
}
```


On Android side you'll need to create a **Firebase** project and configure it (refer to [this guide](https://docs.ep.mburger.cloud/android-docs/messages/prerequisites-for-push-notifications)). Lastly copy the `FCM server key` onto MBurger and give it a good "Update".

Remember for Android to add this to your project build.gradle file:

```dart
classpath 'com.google.gms:google-services:4.3.5'
```

and this to your app build.gradle

```dart
apply plugin: 'com.google.gms.google-services'
```

You are almost done, it's time to code!

 

### Initialize MBMessages

This is a really easy part. You'll need to initialize **MBurger** and add **MBMessages** as a plugin, so it can be initialized and you can instantaneously start receiving messages.

Let's head over to your main widget and **initialize MBurger** with your personal API Key:

```dart
void main() {
  runApp(MyApp());
}

class MyApp extends StatefulWidget {
  @override
  _MyAppState createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
  @override
  void initState() {
    MBManager.shared.apiToken = "MY_API_KEY";
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'MBMessages',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: MyHomePage(title: 'Flutter MBMessages'),
    );
  }
}
```

This way you'll have initialized **MBurger**, now we need to add **MBMessages** and initialize it with the key provided on MBurger. 

```dart
MBMessages.pushToken = "MY_ENGAGEMENT_TOKEN";
MBManager.shared.plugins = [MBMessages()];
```

Next you'll need to use `MBMessages.configurePush` and implement these methods:

- `onNotificationArrival` -> called when a Push Notification arrives on your device
- `onNotificationTap` -> called when a Push Notification is tapped

Lastly you'll need to set the `Android notification channel` for push notifications. You should provide a **name**, **description** and **id** for your channel as well as an icon stored in `drawable` or `mipmap` folders on Android part. 

```dart
MBMessages.configurePush(
      onNotificationArrival: (notification) {
        print("Notification arrived: $notification");
      },
      onNotificationTap: (notification) {
        print("Notification tapped: $notification");
      },
      androidNotificationsSettings: MPAndroidNotificationsSettings(
        channelId: 'messages_example',
        channelName: 'mbmessages',
        channelDescription: 'mbmessages',
        icon: '@mipmap/ic_launcher',
      ),
    );
```

Next you'll need to implement the `onToken` method found on **MBMessages**. This is called when you register your device for receiving push notifications. You can easily then **register to the topics** you want after it. **MBMessages** provides already 2 "standard" topics, one for all users and one dedicated to single devices:

```dart
await MBMessages.projectPushTopic(),
await MBMessages.devicePushTopic(),
```

The code for this step will result like this:

```dart
MBMessages.onToken = (token) async {
      print("Token received $token");
      await MBMessages.registerDevice(token).catchError(
        (error) => print(error),
      );
      await MBMessages.registerToTopics(
        [
          await MBMessages.projectPushTopic(),
          await MBMessages.devicePushTopic(),
        ],
      );
      print('Registered');
    };
```

Lastly you'll need to **request a token** from Firebase and APNS, then if you followed this tutorial your device will be registered for push notifications.

```dart
    await MBMessages.requestToken().catchError(
      (error) => print(error),
    );
```

That's it! You have set up push notifications!

 

### Try it!

Now it's time to check if everything is working properly! On MBurger click on **Engagement** -> **Messages**. Create a new push message and see the magic unfolds!


![Alt Text](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/j19smjnviit40qlzwxlz.png)
 

### Where to go now?

With MBMessage you can also create awesome in-app messages and handle Push Notifications in a more detailed way, check out the [pub.dev page](https://pub.dev/packages/mbmessages) to know more!

 

Wish to check on more awesome Flutter tutorials? [Click here](https://theotherdevs.com/getting-to-know-flutter/)!