Flutter Setup


Send push notifications to your Flutter app with Pushy.

At any time, you may refer to our Flutter demo project for a working demo.

Create an App

Note: No credit card needed. Upgrade to the Pro plan when you're ready by visiting the Billing page.


Please ensure the Android Package Name & iOS Bundle ID you enter precisely match the ones configured in your project files, as they are used to automatically link your client apps with the Pushy Dashboard app having the same Android Package Name & iOS Bundle ID.

Note: If you have already created an app in the Pushy Dashboard for another platform, simply configure your existing dashboard app with your Android Package Name & iOS Bundle ID in the App Settings tab and proceed to the next step.

Click Create and proceed to the next step.

Get the SDK

Install version 2.0.28 of our Flutter SDK by editing the pubspec.yaml in the root directory of your project and adding the following under the dependencies section:

pushy_flutter: 2.0.28

Run flutter pub get to fetch the dependency.


Note: Please ensure your Flutter Android project has been updated to Flutter 1.12+ for compatibility with this plugin:

  • Your android/app/src/main/AndroidManifest.xml should contain a <meta-data> attribute labeled flutterEmbedding with a value of 2 inside the <application> tag.

Enable Push Capability (iOS)

Enable the Push Notifications capability manually for your iOS app to register for and receive push notifications. Open your Flutter iOS app in Xcode by running the following command in your project root:

open ios/*.xcworkspace

Then, visit the project editor, select the Runner target, select the Capabilities tab, and turn on the Push Notifications capability:

Note: Xcode should display two checkmarks indicating that the capability was successfully enabled.

Add Blank Swift File

To avoid a compilation error, please add a blank .swift file to your Xcode project, under the Runner target. This file can be empty. When prompted, you may decline the creation of a bridging header for your project.


You may close the Xcode workspace now.

Modify AndroidManifest

Add the following lines to your android/app/src/main/AndroidManifest.xml, inside the <manifest> tag:

<!-- Pushy Permissions -->
                                    
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.WAKE_LOCK" />
<uses-permission android:name="android.permission.POST_NOTIFICATIONS" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
<uses-permission android:name="android.permission.SCHEDULE_EXACT_ALARM" />

<!-- End Pushy Permissions -->

You should manually omit any permission declarations that your app already asks for.


Additionally, add the following declarations inside the <application> tag:

<!-- Pushy Declarations -->

<!-- Internal Notification Receiver -->
<!-- Do not modify - internal BroadcastReceiver that sends notifications to your Flutter app -->
<receiver android:name="me.pushy.sdk.flutter.internal.PushyInternalReceiver" android:exported="false">
    <intent-filter>
        <!-- Do not modify this -->
        <action android:name="pushy.me" />
    </intent-filter>
</receiver>

<!-- Pushy Update Receiver -->
<!-- Do not modify - internal BroadcastReceiver that restarts the listener service -->
<receiver android:name="me.pushy.sdk.receivers.PushyUpdateReceiver" android:exported="false">
    <intent-filter>
        <action android:name="android.intent.action.MY_PACKAGE_REPLACED" />
    </intent-filter>
</receiver>

<!-- Pushy Boot Receiver -->
<!-- Do not modify - internal BroadcastReceiver that restarts the listener service -->
<receiver android:name="me.pushy.sdk.receivers.PushyBootReceiver" android:exported="false">
    <intent-filter>
        <action android:name="android.intent.action.BOOT_COMPLETED"/>
    </intent-filter>
</receiver>

<!-- Pushy Socket Service -->
<!-- Do not modify - internal service -->
<service android:name="me.pushy.sdk.services.PushySocketService" android:stopWithTask="false" />

<!-- Pushy Job Service (added in Pushy SDK 1.0.35) -->
<!-- Do not modify - internal service -->
<service android:name="me.pushy.sdk.services.PushyJobService"
    android:permission="android.permission.BIND_JOB_SERVICE"
    android:stopWithTask="false" />

<!-- End Pushy Declarations -->
Configure ProGuard

Flutter comes preconfigured with ProGuard. Please make sure the following lines are present in your android/app/proguard-rules.pro file (please create this file if it doesn't exist yet):

-dontwarn me.pushy.**
-keep class me.pushy.** { *; }
-keep class androidx.core.app.** { *; }
-keep class android.support.v4.app.** { *; }
Modify Flutter App

Import pushy_flutter by adding the following to the top of your lib/main.dart file:

import 'package:flutter/services.dart';
import 'package:pushy_flutter/pushy_flutter.dart';

Invoke Pushy.listen() in your lib/main.dart file's initState() method so that Pushy's internal notification listening service will start itself, if necessary:

// Start the Pushy service
Pushy.listen();

Note: If your main.dart does not yet have an initState(), simply define it under your State<> class, e.g. _MyHomePageState:

@override
void initState() {
    super.initState();
    
    // Start the Pushy service
    Pushy.listen();
}
Register Devices

Users need to be uniquely identified to receive push notifications.

Every user is assigned a unique device token that you can use to push it at any given time. Once the user has been assigned a device token, it should be stored in your application's backend database. When you're ready to push the device, your backend server will send its token to our REST API, and we'll deliver the push notification to the corresponding device.


Add the following method to your application to register the device for notifications:

Future pushyRegister() async {
    try {
        // Register the user for push notifications
        String deviceToken = await Pushy.register();

        // Print token to console/logcat
        print('Device token: $deviceToken');

        // Display an alert with the device token
        showDialog(
            context: context,
            builder: (BuildContext context) {
            return AlertDialog(
                title: Text('Pushy'),
                content: Text('Pushy device token: $deviceToken'),
                actions: [ ElevatedButton( child: Text('OK'), onPressed: () { Navigator.of(context, rootNavigator: true).pop('dialog'); } )]
            );
        }
        );
        
        // Optionally send the token to your backend server via an HTTP GET request
        // ...
    } catch (error) {
        // Display an alert with the error message
        showDialog(
        context: context,
        builder: (BuildContext context) {
            return AlertDialog(
                title: Text('Error'),
                content: Text(error.toString()),
                actions: [ ElevatedButton( child: Text('OK'), onPressed: () { Navigator.of(context, rootNavigator: true).pop('dialog'); } )]
            );
        }
        );
    }
}

Then, invoke this method, possibly in initState():

@override
void initState() {
    super.initState();

    // ...

    // Register the user for push notifications
    pushyRegister();
}
Listen for Notifications

Add the following method to your main.dart file, right after the import statements, and outside any Widget class declaration, to process push notifications in the background via a Flutter background isolate:

// Please place this code in main.dart,
// After the import statements, and outside any Widget class (top-level)

@pragma('vm:entry-point')
void backgroundNotificationListener(Map<String, dynamic> data) {
    // Print notification payload data
    print('Received notification: $data');

    // Notification title
    String notificationTitle = 'MyApp';

    // Attempt to extract the "message" property from the payload: {"message":"Hello World!"}
    String notificationText = data['message'] ?? 'Hello World!';

    // Android: Displays a system notification
    // iOS: Displays an alert dialog
    Pushy.notify(notificationTitle, notificationText, data);

    // Clear iOS app badge number
    Pushy.clearBadge();
}

Feel free to modify this sample code to suit your own needs.


Call the Pushy.setNotificationListener(backgroundNotificationListener) method after Pushy.listen() to configure the background notification listener:

// Enable in-app notification banners (iOS 10+)
Pushy.toggleInAppBanner(true);

// Listen for push notifications received
Pushy.setNotificationListener(backgroundNotificationListener);
Listen for Notification Click

Optionally call the Pushy.setNotificationClickListener((data) => {}) method from your application (inside initState()) to listen for when the user taps your notifications:

// Listen for notification click
Pushy.setNotificationClickListener((Map<String, dynamic> data) {
    // Print notification payload data
    print('Notification click: $data');

    // Extract notification messsage
    String message = data['message'] ?? 'Hello World!';

    // Display an alert with the "message" payload value
    showDialog(
    context: context,
    builder: (BuildContext context) {
        return AlertDialog(
            title: Text('Notification click'),
            content: Text(message),
            actions: [ ElevatedButton( child: Text('OK'), onPressed: () { Navigator.of(context, rootNavigator: true).pop('dialog'); } )]
        );
    });

    // Clear iOS app badge number
    Pushy.clearBadge();
});
Custom Notification Icon (Android)

Optionally configure a custom notification icon for incoming Android notifications by placing icon file(s) in android/app/src/main/res/mipmap-* and adding the following lines of code inside your android/app/src/main/AndroidManifest.xml:

Find:

<!-- Pushy Declarations -->

Add below:

<!-- Custom Notification Icon -->
<meta-data
    android:name="me.pushy.sdk.notification.icon"
    android:resource="@mipmap/ic_notification" />

Note: If you don't specify a custom notification icon, a generic icon will be displayed instead.

Parse Notification Data

Any payload data that you send with your push notifications is made available to your app via the data parameter of your notification listener.

If you were to send a push notification with the following payload:

{"id": 1, "success": true, "message": "Hello World"}

Then you'd be able to retrieve each value from within your notification listener callback like so:

int id = data['id']; // number
bool success = data['success']; // bool
String message = data['message']; // string

Note: Unlike GCM / FCM, we do not stringify your payload data, except if you supply JSON objects or arrays.

Subscribe to Topics

Optionally subscribe the user to one or more topics to target multiple users with a shared interest when sending notifications.

Depending on your app's notification criteria, you may be able to leverage topics to simply the process of sending the same notification to multiple users. If your app only sends personalized notifications, skip this step and simply target individual users by their unique device tokens.


Add the following code to your application to subscribe the user to a topic:

try {
    // Make sure the user is registered
    if (await Pushy.isRegistered()) {
        // Subscribe the user to a topic
        await Pushy.subscribe('news');

        // Subscribe successful
        print('Subscribed to topic successfully');
    }
} catch (error) {
    // Subscribe failed, notify the user
    showDialog(
        context: context,
        builder: (BuildContext context) {
        return AlertDialog(
            title: Text('Subscribe failed'),
            content: Text(error.toString()),
            actions: [ ElevatedButton( child: Text('OK'), onPressed: () { Navigator.of(context, rootNavigator: true).pop('dialog'); } )]
            );
        }
    );
}

Note: Replace news with your own case-sensitive topic name that matches the following regular expression: [a-zA-Z0-9-_.]{1,100}.


You can then notify multiple users subscribed to a certain topic by specifying the topic name (prefixed with /topics/) as the to parameter in the Send Notifications API.

Setup APNs Authentication (iOS)

Configure the Pushy dashboard with an APNs Auth Key in order to send notifications to your iOS users.

Pushy routes your iOS push notifications through APNs, the Apple Push Notification Service. To send push notifications with APNs, we need to be able to authenticate on behalf of your app. This is achieved by generating an APNs Auth Key and uploading it to the Dashboard.


In the Apple Developer Center, visit the Auth Keys creation page, enter a key name, and choose Apple Push Notifications service (APNs).

Click Continue and download the .p8 key file:



Note: Keep track of the assigned Key ID for the next step.


Visit the Pushy Dashboard -> Click your app -> App Settings -> Configure APNs Auth ().

Fill in the following:

  1. APNs Auth Key - drag and drop the auth key .p8 file from the previous step
  2. Key ID - the Key ID assigned to the key you downloaded in the previous step
  3. Team ID - the Team ID of your Apple Developer Account, as specified in Membership Details

Click Upload to finish setting up APNs authentication for your app.

Note: Avoid revoking your APNs Auth Key in the Apple Developer Center. Otherwise, you will not be able to send notifications with Pushy. If you think your key was compromised, generate a new one in the Apple Developer Center. Then, upload it to the Dashboard. Finally, revoke your old key in the Apple Developer Center.

Add Support for Flutter Web (Optional)

If your Flutter app also targets the Web platform, follow the instructions below.


Import version 1.0.23 of our Web Push SDK by adding the following line to the <head> tag of your project's web/index.html file:

<script src="https://sdk.pushy.me/web/1.0.23/pushy-sdk.js"></script>

Next, find the following line of code inside the web/index.html:

serviceWorker: {

Add below:

serviceWorkerUrl: 'service-worker.js',

Create a file called service-worker.js inside web/ with the following contents:

// Import Pushy Service Worker 1.0.23
importScripts('https://sdk.pushy.me/web/1.0.23/pushy-service-worker.js');

This file must be accessible at https://example.com/service-worker.js, where example.com is your website hostname.

Next, find the following line of code inside lib/main.dart:

Pushy.listen();

Add below:

// Set Pushy App ID (required for Web Push)
Pushy.setAppId('YOUR_APP_ID');

Note: Please make sure to replace YOUR_APP_ID with your Pushy App ID (Pushy Dashboard -> Click your app -> App Settings -> App ID):

Build and Test

Run your app on each platform to make sure everything works as expected:

flutter run
Send Test Notification

Input a device token and select your app to send a test push notification:

Note: You can specify a topic instead of a device token (i.e. /topics/news). Also, if your app is not automatically detected, please manually copy the Secret API Key from the Dashboard and paste it into the form.

Did you receive the notification? If not, reach out, we'll be glad to help.


Congratulations on implementing Pushy in your Flutter app!

To start sending push notifications to your users, start persisting device tokens in your backend, and invoke the Send Notifications API when you want to send a notification. Follow our step-by-step guide: