SDK Integration

Flutter Package

Onboarding Checklist: Flutter

Please find the Onboarding Checklist for Swift and Flutter below. Follow the titles in the checklist to ensure you have completed each essential step in your onboarding process with Netmera.

Step 1: Install Flutter

To use the Netmera Flutter SDK in your project, follow these steps:

  1. Add the following lines to your pubspec.yaml file under the dependencies section:

dependencies:
  netmera_flutter_sdk: ^x.x.x
  1. Install the package using the command:

$ flutter pub get

No additional Netmera SDK libraries are required for Android or iOS.

Step 2: Setup Android

1. Netmera Android Onboarding

In Netmera Panel:

  • Navigate to Developers > Netmera Onboarding.

  • Select Android and click Start to proceed.

2. Create a Firebase Configuration

Netmera uses Firebase Cloud Messaging (FCM) for delivering push notifications.

  1. Go to the Firebase Developers Console and create a Firebase project.

  2. Generate a new Private Key (JSON file) for your project.

  3. Upload this file in Netmera Panel > Developers > Netmera Onboarding > Android > Step 2: Create A Firebase Configuration > FCM Service Account Key.

3. Select a Target SDK

Choose the Flutter based on your application framework.

4. Integrate and Initialize Flutter SDK

5. Integrate Netmera

  1. Project’s build.gradle File

Add the following to your project-level build.gradle file:

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

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

allprojects {
    repositories {
        google()
        jcenter()
        maven { url 'https://maven.google.com'}
        maven {url 'https://developer.huawei.com/repo/'}
    }
}
  1. App’s build.gradle File

Add the required dependency and plugins to your app-level build.gradle file:

 dependencies {
 
     implementation 'androidx.core:core:X.X.X'
     
 }
  1. At the top of your app’s build.gradle, include:

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

Important Note for Obfuscation:

If your code is obfuscated, there is no need to add any special rules for Netmera. Its functionality is unaffected by code obfuscation.

6. Initialize Netmera

  1. Create the 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) // Enable Netmera logs.
            .build(this);
        FNetmera.initNetmera(fNetmeraConfiguration); 
    }
}
  1. Set Up Event Handlers in Dart

Inside your Dart class, add the following code to set up event handlers for push notifications.

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
  );
}

7. Android 13 Push Notification Permissions

Android 13 introduced significant changes to how push notification permissions are handled.

  • Increased User Control: Apps targeting API Level 33 and above now have more control over when and how they request push notification permissions. This allows for a more user-friendly and context-aware permission request experience.

  • Automatic Permission Requests for Older Apps: For apps targeting API Level 32 and below running on Android 13, the system automatically prompts the user for push notification permission when the app creates its first notification channel.

Impact on Netmera SDK Users:

The Netmera SDK initializes and creates notification channels during the app's startup. Consequently:

  • On Android 13: For apps targeting API Level 32 and below, this initialization process will trigger the automatic system prompt for push notification permission.

  • On Android 12 and below: The system generally assumes push notification permission has already been granted.

Push Permission Methods in Netmera SDK

For Android apps targeting API Level 33, the Netmera SDK provides two key methods to handle notification permissions:

  1. Requesting Notification Permissions

 Netmera.requestPushNotificationAuthorization();

Use this method to request notification permissions from the user. Call this method when you need to prompt the user for permissions at any time.

Push Enable/Disable User Flow:

  1. Granting Permission:

    • The user triggers requestNotificationPermissions(), and if they grant permission, a push enable request is sent.

  2. Handling Denial:

    • If the user denies permission, avoid resending the request immediately (as recommended by Google). Instead, the SDK opens the app's notification settings. The user can grant permission from the settings and return to the app, where a push enable request is sent.

  3. Denying Permission:

    • If the user triggers requestNotificationPermissions() and denies permission, a push disable request is sent.

  4. Reattempt After Denial:

    • If denied, avoid immediate re-request. The SDK will open the app's notification settings. If the user cancels (presses the back button), a push disable request is sent.

  1. Checking Notification Status

This method allows checking whether the necessary permissions for the application have been obtained.

Netmera.checkNotificationPermission().then((status) {
      // NotificationPermissionStatus.notDetermined
      // NotificationPermissionStatus.blocked
      // NotificationPermissionStatus.denied
      // NotificationPermissionStatus.granted
 });

Responses

When this method is called, it would return one of the following responses:

  1. NOTDETERMINED The user has opened the app but hasn't made a decision about notification permissions yet.

  2. GRANTED The user has granted notification permission, and the app can send notifications.

  3. DENIED The user has denied permission or has blocked notifications through system settings.

Step 3: Setup iOS

1. Create an Apple Push Notification Certificate

  1. Log in to developer.apple.com with your Apple Developer account.

  2. Generate an Apple Push Notification Certificate for your app.

  3. Export the certificate using Keychain Access on your Mac.

  4. Upload the exported certificate to the Netmera panel by navigating to Developer > Push Backends > iOS in the left menu.

Bundle IDs should match on your project, certificate and panel:

Ensure that the certificate you upload to the panel matches the bundle ID of your project. Additionally, set your project's bundle ID in the panel to ensure consistency. The bundle ID of your project, the certificate, and the one specified in the panel must all align.

Certificate types:

  • For apps downloaded from the App Store or tested via TestFlight, the certificate type should be set to "prod".

  • For apps built directly from Xcode, the certificate type must be set to "dev".

If you have problems sending push notifications when you build from Xcode, verify the certificate type on the Developer > Push Backends > iOS page in Panel.

Creating an APNS .p12 Certificate

Install Pods

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

$ pod install

Swift Configuration

If you're using Swift, add the following imports in your Runner-Bridging-Header.h file:

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

3. Initialize Netmera

To enable message sending from iOS to Dart, configure your AppDelegate class as follows:

import UIKit
import Flutter

// This function is needed for sending messages to the Dart side (Setting the callback function).
func registerPlugins(registry: FlutterPluginRegistry) {
    GeneratedPluginRegistrant.register(with: registry)
};

@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 for earlier iOS versions
        }

        // Trigger onPushReceive when the app is killed and a push notification is clicked
        if let notification = launchOptions?[.remoteNotification] {
            FNetmeraService.handleWork(ON_PUSH_RECEIVE, dict: ["userInfo": notification])
        }

        // This function is needed for sending messages to the Dart side.
        NetmeraFlutterSdkPlugin.setPluginRegistrantCallback(registerPlugins)

        FNetmera.logging(true) // Enable Netmera logging
        FNetmera.initNetmera("<YOUR-NETMERA-KEY>") // Initialize Netmera
        FNetmera.setPushDelegate(self)
        Netmera.setAppGroupName(<YOUR-APP-GROUP-NAME>) // Set app group name

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

    // Handle registration for push notifications
    override func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
        FNetmeraService.handleWork(ON_PUSH_REGISTER, dict: ["pushToken": deviceToken])
    }

    // Handle receiving remote notifications
    override func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable: Any]) {
        FNetmeraService.handleWork(ON_PUSH_RECEIVE, dict: ["userInfo": userInfo])
    }

    // Handle foreground push notifications (iOS 10+)
    @available(iOS 10.0, *)
    override func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {
        completionHandler([UNNotificationPresentationOptions.alert])

        if UIApplication.shared.applicationState == .active {
            FNetmeraService.handleWork(ON_PUSH_RECEIVE, dict: ["userInfo": notification.request.content.userInfo])
        } else {
            FNetmeraService.handleWork(ON_PUSH_RECEIVE_BACKGROUND, dict: ["userInfo": notification.request.content.userInfo])
        }
    }
}

Triggering Dart Method

When you trigger FNetmeraService.handleWork(ON_PUSH_RECEIVE, dict: ["userInfo": userInfo]) in AppDelegate, the following Dart method will be triggered:

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

This ensures that push notifications from iOS are correctly handled and passed to your Dart code.

4. Request Push Notification Authorization

In Flutter applications targeting iOS, it is necessary to request notification permissions. To request notification permissions on iOS, add the following code to your Flutter app:

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

Example Project

For a practical example, check out the Netmera Flutter Example Project on GitHub, which shows how to integrate the Flutter SDK and request notification authorization on iOS.

5. Configure Xcode Push Notifications Settings

  1. Open your project in Xcode.

  2. Navigate to Signing & Capabilities.

  3. Click + Capability and select Push Notifications.

Email Subscription Preferences (Optional)

Use the following methods to manage email subscription preferences in the Netmera SDK:

  • Check if email subscription is allowed:

    Netmera.isAllowedEmailSubscription()
  • Set email subscription preference:

    Netmera.setAllowedEmailSubscription(true);  // Allow subscriptions
    Netmera.setAllowedEmailSubscription(false); // Disallow subscriptions

iOS 10 Media Push

For detailed instructions on using iOS 10 Media Push, refer to the specific documentation > Push Notifications.

Step 4. Calling Dart Methods

onPrem Configuration

If you're using an onPrem setup, you need to set the base URL for Netmera. You can do this using the following method. This will configure the base URL for your on-premise Netmera setup.

Netmera.setBaseUrl("<YOUR_BASE_URL>");

For further details, refer to the documentation for more information.

Flutter SDK Integration Complete

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:

  • Standard Push Notifications

  • Interactive Push Notifications

  • Widgets

  • Push Notifications with Deeplinks

Last updated

Was this helpful?