How to build cross-platform notifications in your Flutter app with Pusher Beams
Familiarity with Flutter environment and Dart language would be beneficial to complete this tutorial, but aren't compulsory as this is a step by step guide.
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
1. 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:
$ flutter devices
2 connected devices:
Android 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.
2. 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.
3. 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:
buildscript {
// Your config...
repositories {
google()
// Your repositories...
}
dependencies {
// Your dependencies...
// Add this line
classpath 'com.google.gms:google-services:4.2.0'
}
}
- 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.
4. 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()
:
import 'package:pusher_beams/pusher_beams.dart';
void main() async {
WidgetsFlutterBinding.ensureInitialized();
const instanceID = '00000000-0000-0000-0000-000000000000';
await PusherBeams.instance.start(instanceID);
await PusherBeams.instance.setDeviceInterests(['debug-new', ‘hello’]);
runApp(const MyApp());
}
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:
await PusherBeams.instance.addDeviceInterest('bananas');
await PusherBeams.instance.removeDeviceInterest('bananas');
await PusherBeams.instance.clearDeviceInterests();
5. 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.
6. 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:
final BeamsAuthProvider provider = BeamsAuthProvider()
..authUrl = 'https://some-auth-url.com/secure'
..headers = {'Content-Type': 'application/json'}
..queryParams = {'page': '1'}
..credentials = 'omit';
await PusherBeams.instance.setUserId(
'User-id',
provider,
(error) => {
if (error != null) { print(error) }
// Success! Do something...
}
);
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.
16 February 2022
by Felipe Benevides, Meena Alfons