Flutter SDK Integration

Quick Steps Guidelines

Step 1. Install Flutter

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

Step 2. Android Setup

Create and configure a project on Firebase Developers Console and complete the following steps for Android Setup.

Step 3. iOS Setup

Navigate to the iOS folder in your terminal and run the commands in Step 3 to install dependencies.

Step 4. Calling Dart Methods

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

Flutter SDK integration completed 👏

You may also check out the detailed document here.

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. Android Setup

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'
  1. 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); 
        }
    }
  1. Inside Dart Class:

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

Step 3. iOS Setup

To set up Netmera for iOS, follow these steps:

  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"
  1. 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");
}

For further information > You may check Step 2. Android Setup.

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

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

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