How to build cross-platform notifications in your Flutter app with Pusher Beams

Introduction

In this tutorial, we’ll create a Flutter project from scratch using Pusher Beams to send realtime, transactional push notifications to your users.

Flutter is an open-source framework created by Google for building beautiful, natively compiled, multi-platform applications from a single codebase.

You can use Beams to add transactional cross-platform push notifications to your Flutter app. Aside from bypassing the complex integration and maintenance associated with notification gateways, Beams is extremely flexible, scalable and reliable, and includes valuable insights into your notification performance.

Set up

To complete this tutorial you'll need the following:

  • A Pusher account and a Beams project set up in the dashboard. If you don't already have one you can sign up for the sandbox plan which is completely free and will be more than ample to complete this sample project so you can start experimenting with notifications for Flutter.
  • The latest version of Flutter installed on your system. If you’re just starting with Flutter, you can follow the tutorial here to install.
  • An IDE of your choice.

Platform support

  • Android support for API level greater than 19
  • iOS > 10.0
  • Note that the Beams Flutter SDK is currently operating for Android and iOS only. If you’re planning to integrate the SDK for full cross-platform functionality, keep an eye on our announcements to see when the Web SDK is out of testing.

All events/connections can be viewed on the debug console on the Pusher dashboard.

Adding Beams to your Flutter app

Create a Flutter app

If you already have a Flutter project you can jump to creating a Beams instance.

If you’re just starting with Flutter, you’ll first need to install it. Then, you can create a new Flutter project:

$ flutter create beams_example

Before running the project, make sure you boot up the emulator you want to run the application. To configure it, you can read the relevant part of the official documentation according to your operating system.

To list all devices available for your application, you can run:

1$ flutter devices
22 connected devices:
3
4Android SDK 30 • emulator-5554 • android-x86    • Android 11 (API 30) (emulator)

Choose the device you want to run the app on and Flutter will start building the application and then launch it on the chosen device by running the following command:

$ flutter run -d emulator-5554

In this example, the application will be running on an Android emulator.

Create a Beams instance

Create one Beams instance to be used in your app. After creating an instance, you will find options for setting up different platforms: Android, iOS, and Web.

This SDK currently supports Android and iOS.

Platform specific settings

Android

To set up Pusher Beams for Android, you must configure FCM and Google Services by following these steps:

  • Create a Firebase project
  • Set up the FCM Server Key in the instance settings in Pusher Beams.
  • Create a new Android app in Firebase with the package name of your choice
  • Download the google-services.json file from the Firebase console.
  • Copy this google-services.json to android/app/google-services.json.
  • Add the following line inside the project-level build.gradle in /android/build.gradle:
1buildscript { 
2   // Your config... 
3   repositories { 
4      google() 
5      // Your repositories... 
6   }         
7
8   dependencies { 
9      // Your dependencies... 
10      // Add this line 
11      classpath 'com.google.gms:google-services:4.2.0' 
12   } 
13}
  • In the app-level build.gradle at my-app/android/app/build.gradle, add the following line at the end:
apply plugin: 'com.google.gms.google-services'
  • Change the minSdkVersion to at least 19 inside the app-level build.gradle

iOS

To set up Pusher Beams for iOS, you must configure APNS. You can read more about it in our official documentation.

The following steps are needed to set up the iOS project:

  • Open the iOS project in XCode (my_app/ios/Runner.xcworkspace)
  • Go to Build Settings and change the “iOS Deployment Target” to iOS 10.0 or above.
  • Go to “Signing and Capabilities” and set the “Bundle Identifier” to the App ID you created in your Apple Account.
  • While inside “Signing and Capabilities”, add the following capabilities. You can read more in our docs about enabling capabilities within your iOS app:
    • “Push Notifications”
    • “Background Modes” => “Remote Notifications”
  • Make sure to close Xcode afterwards.

It is worth noting that server side event-driven push notifications do not work on iOS simulators. You’ll need to use a real device to test this functionality.

Getting started with the library

First, you need to install Pusher Beams dependencies by running the following command:

$ flutter pub add pusher_beams

Now it’s time to use Pusher Beams in your code. The following snippet includes the imports and the lines you need to add to your main() function in lib/main.dart file.

Remember to add async beside main():

1import 'package:pusher_beams/pusher_beams.dart';
2
3void main() async {
4  WidgetsFlutterBinding.ensureInitialized();
5
6  const instanceID = '00000000-0000-0000-0000-000000000000';
7  await PusherBeams.instance.start(instanceID);
8  await PusherBeams.instance.setDeviceInterests(['debug-new', ‘hello’]);
9
10  runApp(const MyApp());
11}

Replace the instanceID with the id of the Beams instance you just created.

Notice that in this code, the device subscribes to two interests (“debug-new” and “hello”), and they will be used to publish notifications.

The SDK also provides more ways to add and remove interests by calling:

1await PusherBeams.instance.addDeviceInterest('bananas');
2await PusherBeams.instance.removeDeviceInterest('bananas');
3await PusherBeams.instance.clearDeviceInterests();

Handling notification events in your code

Although push notifications are delivered to the notification center of the device, Pusher Beams SDK provides event listeners that empower you to customize some behaviors in your application. Customization is supported on Android and iOS platforms.

The following two listeners are supported:

  • When interests are added or removed
PusherBeams.instance.onInterestChanges((interests) => print(interests));
  • When a push notification is received while the app is in the foreground
PusherBeams.instance.onMessageReceivedInTheForeground((notification) => print(notification));

When the app is in the foreground, adding this listener lets you control the notification in your app, and it does not go to the notification center. However, when your app is in the background, this listener will not be executed, and the notification will go to the notification center of the device.

Authenticating users

Authenticated Users allows you to securely associate devices with an arbitrary user ID which you set from your server and publish personalized notifications directly to users.

For more information about it, you can read our Authenticated Users documentation.

With Beams Flutter SDK, you can register a new user using this snippet:

1final BeamsAuthProvider provider = BeamsAuthProvider()
2     ..authUrl = 'https://some-auth-url.com/secure'
3     ..headers = {'Content-Type': 'application/json'}
4     ..queryParams = {'page': '1'}
5     ..credentials = 'omit';
6
7await PusherBeams.instance.setUserId(
8   'User-id',
9    provider,
10    (error) => {
11        if (error != null) { print(error) }
12        // Success! Do something...
13    }
14);

If the user wants to log out of your application, you should use .clearAllState() to leave the SDK in an empty state.

If the device was paired with a user and the app is uninstalled without calling this method, Pusher Beams will remove the device.

PusherBeams.instance.clearAllState();

If you want to stop receiving push notifications by deleting all SDK state both remotely and locally, you should use stop() method. Calling this will mean the device will cease to receive push notifications .start must be called if you want to use the SDK again.

PusherBeams.instance.stop();

Full example

For a more detailed example of all those features, we’ve created an application so you can play with the library.

Check out our use cases to read more about what you can build on your Flutter apps using Pusher.