Flutter SDK Integration

Quick Steps Guidelines

Step 1. Install Flutter

Add the following lines to your project

Step 2. Setup Android

Step 3. Setup iOS

Step 4. Calling Dart Methods

If you use onPrem set baseUrl as shown in Step 4.

Flutter SDK integration completed 👏

Step 1. Flutter Installation

To use this package as a library in your Flutter project, follow these steps:

  1. Add the following lines to your project's pubspec.yaml file under the dependencies section.

dependencies:
  netmera_flutter_sdk: ^x.x.xg
  1. You can install packages from the command line with Flutter:

$ flutter pub get

You don't need to include extra Netmera SDK libraries for both native sides (Android & iOS).

Step 2. Setup Android

1. Select a Platform

Navigate to Netmera Panel > Developers > Netmera Onboarding and choose Android.

Click on Android > Start to proceed.

2. Create a Firebase Configuration

Netmera uses Firebase Cloud Messaging (FCM) to deliver push messages to the Android devices. Therefore, you should create and configure a project on Firebase Developers Console.

  • At the end of the Firebase configuration, you will have a New Private Key folder of your project. That folder must be uploaded to Developers > Netmera Onboarding > Android > Step 2: Create A Firebase Configuration > FCM Service Account Key section on Netmera Panel.

Firebase Cloud Messaging Configuration

Firebase Cloud Messaging - Generate New Private Key

Upload FCM Service Account Key on Netmera Panel

3. Select a Target SDK

Select the appropriate SDK for your application development framework from the following options: Native Android, Flutter, React Native, Unity. Note: The subsequent instructions on this page are specific to the Flutter SDK.

4. Integrate and Initialize Flutter SDK

⚠️ Warning: Do not use the API key from your test panel when setting up or deploying your production app. Each panel has its own unique API key. Even if you log in with a different account, this encrypted key stays the same. Using the wrong key can result in data being sent to the incorrect environment, causing potential issues or errors in your application.

Update Gradle Files

In your project's build.gradle file, add the following dependencies.

buildscript {
    repositories {
        google()
        jcenter()
        maven {url 'https://developer.huawei.com/repo/'}
    }

    dependencies {
        classpath 'com.android.tools.build:gradle:4.1.3'
        classpath 'com.google.gms:google-services:4.3.5'
        classpath 'com.huawei.agconnect:agcp:1.5.2.300'
    }
}

allprojects {
    repositories {
        google()
        jcenter()
        maven { url 'https://maven.google.com'}
        maven {url 'https://developer.huawei.com/repo/'}
    }
}

In your app's build gradle file, add the following dependency.

 dependencies {
 
     implementation 'androidx.core:core:1.1.0'
     
 }

Add the following into the top of app's build.gradle file.

apply plugin: 'com.google.gms.google-services'
apply plugin: 'com.huawei.agconnect'

Create Application Class (Java)

Create an application class that extends FlutterApplication.

Replace <YOUR GCM SENDER ID>, <YOUR HMS SENDER ID>, and <YOUR NETMERA API KEY> with your actual values.

    public class NMApp extends FlutterApplication {
    
        @Override
        public void onCreate() {
            super.onCreate();
            FNetmeraConfiguration fNetmeraConfiguration = new FNetmeraConfiguration.Builder()
                .firebaseSenderId(<YOUR GCM SENDER ID>)
                .huaweiSenderId(<YOUR HMS SENDER ID>)
                .apiKey(<YOUR NETMERA API KEY>)
                .logging(true) // This is for enabling Netmera logs.
                .build(this);
            FNetmera.initNetmera(fNetmeraConfiguration); 
        }
    }

Inside your Dart class, add the following code to set up event handlers:

void main() {
  initBroadcastReceiver();
  runApp(MyApp());
}

void _onPushRegister(Map<dynamic, dynamic> bundle) async {
  print("onPushRegister: $bundle");
}

void _onPushReceive(Map<dynamic, dynamic> bundle) async {
  print("onPushReceive: $bundle");
}

void _onPushDismiss(Map<dynamic, dynamic> bundle) async {
  print("onPushDismiss: $bundle");
}

void _onPushOpen(Map<dynamic, dynamic> bundle) async {
  print("onPushOpen: $bundle");
}

void _onPushButtonClicked(Map<dynamic, dynamic> bundle) async {
  print("onPushButtonClicked: $bundle");
}

void _onCarouselObjectSelected(Map<dynamic, dynamic> bundle) async {
  print("onCarouselObjectSelected: $bundle");
}

void initBroadcastReceiver() {
  NetmeraPushBroadcastReceiver receiver = new NetmeraPushBroadcastReceiver();
  receiver.initialize(
    onPushRegister: _onPushRegister,
    onPushReceive: _onPushReceive,
    onPushDismiss: _onPushDismiss,
    onPushOpen: _onPushOpen,
    onPushButtonClicked: _onPushButtonClicked,
    onCarouselObjectSelected: _onCarouselObjectSelected
  );
}

Custom Firebase Messaging Integration

If you have a custom Firebase Messaging integration, use the following code:

FirebaseMessaging messaging = FirebaseMessaging.instance;

messaging.getToken(vapidKey: <YOUR_KEY>).then((value) {
  Netmera.onNetmeraNewToken(value);
});

FirebaseMessaging.onMessage.listen((RemoteMessage message) {
     if (Netmera.isNetmeraRemoteMessage(message.data)) {
         Netmera.onNetmeraFirebasePushMessageReceived(message.from, message.data);
     }
});   

Important Note:

If you're building your Flutter project with flutter run --release and need to add the @pragma('vm:entry-point') annotation to the _firebaseMessagingBackgroundHandler method, you can modify the code block as follows.

Adding the @pragma('vm:entry-point') annotation ensures that this method is correctly recognized as an entry point when building your project in release mode. This is important for background message handling in Flutter, and the annotation helps Flutter identify and execute the method as expected.

@pragma('vm:entry-point')
Future<void> _firebaseMessagingBackgroundHandler(RemoteMessage remoteMessage) async {
// handle message
}

Custom Huawei Messaging Integration

If you have a custom Huawei Messaging integration, use the following code.

Push.getTokenStream.listen((String token) {
  Netmera.onNetmeraNewToken(token);
});

Push.onMessageReceivedStream.listen((RemoteMessage remoteMessage) {
  Map<String, String> map = remoteMessage.dataOfMap ?? new Map();
  if (Netmera.isNetmeraRemoteMessage(map)) {
    Netmera.onNetmeraHuaweiPushMessageReceived(remoteMessage.from, map);
  }
});

Android 13 Push Notification Permissions

Applications targeting API Level 33 and above are empowered to request push notification permissions from users as needed. This decision is in the hands of the Android operating system.

For all applications with a target level below API Level 33, when the application is running on a device with Android 13 or higher, the operating system will automatically prompt the user for these permissions during the initial creation of notification channels.

Since Netmera SDK creates notification channels after receiving the initialization response, and we advise you to call the init method at the application level, this permission request will be triggered automatically as soon as the application is launched. However, this automatic request applies only to applications targeting Android API Level 32 and below, and it takes effect on devices running Android 13 or higher.

On devices running Android 12 and earlier, the system already behaves as if this permission has been granted by default.

Push Permission Methods in Netmera SDK

If you don't request notification permission at runtime, you can request it by calling the requestPushNotificationAuthorization() method. Note: Notification runtime permissions are required on Android 13 (API 33) or higher. Therefore, before calling the method, make sure your project targets an API of 33 and above.

 Netmera.requestPushNotificationAuthorization();

You can call the areNotificationsEnabled() method if you need to know the status of permissions.

 Netmera.areNotificationsEnabled().then((enabled) {
      // Use the enabled status of permission as boolean
 });

This method triggers the necessary methods to send a request for permissions to the system at any time.

Push Enable/Disable Notes:

  1. The users triggers the requestNotificationPermissions() method, the user grants permission (push enable request is sent).

After the customer receives a denial, they send the same request again (it is recommended by Google not to resend it immediately after receiving a denial), and the SDK opens the Notification settings that are specific to that application on the operating system. The user grants notification permission from the settings and returns to the application (push enable request is sent).

  1. The users triggers the requestNotificationPermissions() method, the user denies permission (push disable request is sent).

After the customer receives a denial, they send the same request again (it is recommended by Google not to resend it immediately after receiving a denial), and the SDK opens the Notification settings that are specific to that application on the operating system. The user cancels (presses the back button) (push disable request is sent).

Step 3. Setup iOS

To get a visual guide on how to integrate Netmera into your iOS app, you may watch our iOS integration video below.

Below you may also see the written steps of creating an Apple Push Notification Certificate.

Creating an Apple Push Notification Certificate

You may also see these steps in the video above (iOS Integration Developer Guide Video).

  1. Log in to https://developer.apple.com with your Apple ID.

  2. Click on "Certificates, Identifiers & Profiles."

  3. Press the '+' button and select "Apple Push Notification service SSL" (Sandbox & Production), then proceed.

  4. Choose your App ID and proceed.

  5. Follow general instructions to generate a Certificate Signing Request (CSR) file and upload it on the next page.

  6. Download the generated certificate and add it to your Keychain.

  7. Right-click on the certificate signed with your private key and export it.

Uploading the Created Push Certificate to the Panel:

  1. Go to Developers > Push Backends > IOS.

  2. In the opened window under the APNS Certificate section, upload the created certificate.

  3. Enter the value used when extracting the certificate, which corresponds to the Bundle ID of your application, into the Topic (Bundle ID) field.

  4. Optionally, you can create a password for your certificate.

  5. The Certificate Type field should be set to "Prod" if your application is live, ensuring users can receive push notifications. For testing environments during developers' testing, when the build is obtained with a cable, the certificate type should be set to "Dev" for successful push tests.

1. Enable Push Notifications for Your Project

We send push notifications using APNS (Apple Push Notification Service). Therefore, you need to obtain an Apple Push Notification Certificate from www.developer.apple.com using your account. Once you have the certificate, you should export it using Keychain Access and add it to the iOS page in the panel's left menu under Developer > Push Backend.

Important Notes on Bundle ID:

Make sure to add the certificate generated with the bundle ID of your project to the panel, and set the bundle ID of your project in the panel as well. The bundle ID of your project, the bundle ID of the certificate, and the bundle ID set in the panel should all match.

In case of having problems sending push notifications when you build from Xcode:

Check the certificate type on the Developer > Backend Transfer > iOS page in the menu on the left. If you downloaded the app from the store or are testing it via TestFlight, the certificate type must be "prod". If you are compiling from Xcode, the certificate type must be selected as "dev".

2. Integrate SDK into Your Project

  1. Navigate to the "iOS" folder in your terminal and run the following command to install dependencies:

$ pod install
  1. If you're using Swift, you'll need to include the following imports in your Runner-Bridging-Header.h file.

#import "FNetmera.h"
#import "FNetmeraService.h"
#import "NetmeraFlutterSdkPlugin.h"

3. Setup Netmera

If you want to enable Android-like message sending from iOS to Dart, consider configuring your AppDelegate class as follows.

import UIKit
import Flutter

@UIApplicationMain
@objc class AppDelegate: FlutterAppDelegate,UNUserNotificationCenterDelegate,NetmeraPushDelegate {

    override func application(_ application: UIApplication,
                didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
    GeneratedPluginRegistrant.register(with: self)

        if #available(iOS 10.0, *) {
        UNUserNotificationCenter.current().delegate = self
    } else {
        // Fallback on earlier versions
    };

        //For triggering onPushReceive when app is killed and push clicked by user
        let notification = launchOptions?[.remoteNotification]
        if notification != nil {
            self.application(application, didReceiveRemoteNotification: notification as! [AnyHashable : Any])
        }

    FNetmera.logging(true) // Enable Netmera logging
    FNetmera.initNetmera("<YOUR-NETMERA-KEY>") //Initializing Netmera packages.
    FNetmera.setPushDelegate(self) //
    Netmera.setAppGroupName("group.com.netmera.flutter") // Your app group name

    return super.application(application, didFinishLaunchingWithOptions: launchOptions)
  }


    override func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
        FNetmeraService.handleWork(ON_PUSH_REGISTER, dict: ["pushToken": deviceToken])
    }

    override func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable : Any]) {
        FNetmeraService.handleWork(ON_PUSH_RECEIVE, dict:["userInfo" : userInfo])
    if UIApplication.shared.applicationState == .active {
    FNetmeraService.handleWork(ON_PUSH_RECEIVE, dict:["userInfo" : userInfo])
    } else {
    FNetmeraService.handleWork(ON_PUSH_RECEIVE_BACKGROUND, dict:["userInfo" : userInfo])
    }
    }


    @available(iOS 10.0, *)
    func userNotificationCenter(_ center: UNUserNotificationCenter,
                                didReceive response: UNNotificationResponse,
                                withCompletionHandler completionHandler:
        @escaping () -> Void) {

        if response.actionIdentifier == UNNotificationDismissActionIdentifier {
            FNetmeraService.handleWork(ON_PUSH_DISMISS,dict:["userInfo" : response.notification.request.content.userInfo])
        }
        else if response.actionIdentifier == UNNotificationDefaultActionIdentifier {
            FNetmeraService.handleWork(ON_PUSH_OPEN, dict:["userInfo" : response.notification.request.content.userInfo])
        }
        completionHandler()
    }

    @available(iOS 10.0, *)
    func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {
        completionHandler([UNNotificationPresentationOptions.alert])
    }
}

For instance, if you trigger FNetmeraService.handleWork(ON_PUSH_RECEIVE, dict:["userInfo" : userInfo]) from AppDelegate, the following Dart method will be triggered

void _onPushReceive(Map<dynamic, dynamic> bundle) async {
  print("onPushReceive: $bundle");
}

4. Request Push Notification Authorization

In Flutter applications targeting iOS, it is necessary to request notification permissions. This can be achieved seamlessly within your Flutter codebase. Below is an example code snippet demonstrating how to request notification authorization specifically for iOS using Netmera's Flutter SDK:

 if (Platform.isIOS) {
      Netmera.requestPushNotificationAuthorization();
    }

Example Project: For a practical demonstration, you can refer to the sample project provided by Netmera on GitHub. The example project showcases how to integrate Netmera's Flutter SDK and includes the code snippet for requesting notification authorization on iOS:

Netmera Flutter Example Project

5. Configure Xcode Push Notifications Settings

Enable push notifications for your app by navigating to Signing & Capabilities > Capability > Push Notifications.

Email Subscription Preferences (optional)

The following methods in iOS are used for managing email subscription preferences within the Netmera mobile SDK. Here's an explanation of each method:

  • This method is used to check whether the user has allowed email subscriptions through the Netmera SDK. It returns a Boolean value.

Netmera.isAllowedEmailSubscription()
  • This method is used to set the user's preference for email subscriptions within the Netmera SDK.

Netmera.setAllowedEmailSubscription(true)
Netmera.setAllowedEmailSubscription(false)

iOS 10 Media Push

For instructions on using iOS 10 Media Push, please refer to the relevant documentation on page Former iOS Push.

Step 4. Calling Dart Methods

onPrem

If you use onPrem set baseUrl,

Netmera.setBaseUrl("")

Feel free to use the following documentation for further information.

Flutter SDK integration completed 👍

Flutter SDK integration has been successfully completed, and your devices are now ready to receive the following types of push notifications sent via the Netmera Dashboard:

  1. Standard Push Notifications

  2. Interactive Push Notifications (If you've configured and published them using the Dashboard)

  3. Push Notifications with Web View Content

  4. Push Notifications with Deeplinks (If your application supports URL Scheme-based deeplinks and you've configured the application's URL Scheme in the Dashboard.)

Last updated