Getting to know Flutter: Easy notifications with MBMessages

Enrico Ori
TheOtherDev/s
Published in
5 min readSep 22, 2021

--

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. 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. Once you’ve done all of this you have to add MBMessages dependency to your project. Head over to this page and add it as your dependency:

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.

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

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

UNUserNotificationCenter.current().delegate = self

The app delegate should look like this.

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). 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:

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

and this to your app build.gradle

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:

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.

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.

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:

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

The code for this step will result like this:

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.

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!

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 to know more!

Wish to check on more awesome Flutter tutorials? Click here!

--

--

Enrico Ori
TheOtherDev/s

Just like the priest of Age Of Empires, I want an army of developers with me!!