netmera_flutter_sdk 2.4.1-alpha01 netmera_flutter_sdk: ^2.4.1-alpha01 copied to clipboard
NETMERA is a Mobile Application Engagement Platform. We offer a series of development tools and app communication features to help your mobile business ignite and soar.
Netmera Flutter SDK #
NETMERA is a Mobile Application Engagement Platform. We offer a series of development tools and app communication features to help your mobile business ignite and soar.
Installation #
For using this package as a library:
- Add this to your package's pubspec.yaml file
dependencies:
netmera_flutter_sdk: ^x.x.x
- You can install packages from the command line with Flutter:
$ flutter pub get
For both native sides(Android & iOS) you don't have to include extra Netmera SDK libraries.
Setup - Android Part #
-
Create and register your app in Firebase console.
-
Download
google-services.json
file and place it into android/app/ folder. -
In your project's build gradle file, add the following dependency.
buildscript {
repositories {
google()
mavenCentral()
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.10'
classpath 'com.huawei.agconnect:agcp:1.6.3.300'
}
}
allprojects {
repositories {
google()
mavenCentral()
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 an application class as shown below.
- Your Application class must extends
FlutterApplication
.
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);
}
}
Setup - iOS Part #
- Navigate to ios folder in your terminal and run the following command.
$ pod install
-
Download
GoogleService-Info.plist
file from Firebase and place it into ios/ folder. -
Enable push notifications for your project
- If you have not generated a valid push notification certificate yet, generate one and then export by following the steps explained in Configuring Push Notifications section of App Distribution Guide
- Export the generated push certificate in .p12 format and upload to Netmera Dashboard.
- Enable Push Notifications capability for your application as explained in Enable Push Notifications guide.
- Enable Remote notifications background mode for your application as explained in Configuring Background Modes guide.
-
If you are using Swift, enter the following in your
Runner-Bridging-Header.h
.
#import "FNetmera.h"
#import "FNetmeraService.h"
#import "NetmeraFlutterSdkPlugin.h"
- If you want to use Android alike message sending from iOS to dart please consider to shape your AppDelegate class as following.
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]) {
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 example if you trigger FNetmeraService.handleWork(ON_PUSH_RECEIVE, dict:["userInfo" : userInfo])
from AppDelegate, in the dart part the following method will be triggered.
void _onPushReceive(Map<dynamic, dynamic> bundle) async {
print("onPushReceive: $bundle");
}
- In order to use iOS10 Media Push, follow the instructions in Netmera Product Hub. Differently, you should add the pods to the top of the
Podfile
as below.
// For receiving Media Push, you must add Netmera pods to top of your Podfile.
pod "Netmera", "3.22.0-WithoutDependency"
pod "Netmera/NotificationServiceExtension", "3.22.0-WithoutDependency"
pod "Netmera/NotificationContentExtension", "3.22.0-WithoutDependency"
Setup - Dart Part #
- You can set your own push callbacks in Dart side as following. These methods are optional.
void initBroadcastReceiver() {
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");
}
NetmeraPushBroadcastReceiver().initialize(
onPushRegister: _onPushRegister,
onPushReceive: _onPushReceive,
onPushDismiss: _onPushDismiss,
onPushOpen: _onPushOpen,
onPushButtonClicked: _onPushButtonClicked,
onCarouselObjectSelected: _onCarouselObjectSelected,
);
}
-
You need a background handler to be able to listen incoming push notifications when the application is in the background or terminated state. You can add this handler as follows. When received, an isolate is spawned (Android only, iOS does not require a separate isolate) allowing you to handle messages even when your application is not running.
Note: Since the handler runs in its own isolate outside your applications context, it is not possible to update application state or execute any UI impacting logic. You can, however, perform logic such as HTTP requests, perform IO operations etc.
// This method must be a top-level function
@pragma('vm:entry-point')
void _onPushReceiveBackgroundHandler(Map<dynamic, dynamic> bundle) async {
print("onPushReceiveBackground: $bundle");
}
void main() {
WidgetsFlutterBinding.ensureInitialized();
// This method must be called before the runApp and the provided handler must be a top-level function.
NetmeraPushBroadcastReceiver.onPushReceiveBackground(_onPushReceiveBackgroundHandler);
runApp(MyApp());
}
- If you have custom Firebase Messaging integration, please see usage below.
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);
}
});
Future<void> _firebaseMessagingBackgroundHandler(RemoteMessage message) async {
await Firebase.initializeApp();
if (Netmera.isNetmeraRemoteMessage(message.data)) {
Netmera.onNetmeraFirebasePushMessageReceived(message.from, message.data);
}
}
- If you build your project with
flutter run --release
, please add@pragma('vm:entry-point')
annotation to your_firebaseMessagingBackgroundHandler
method as in the following code block.
@pragma('vm:entry-point')
Future<void> _firebaseMessagingBackgroundHandler(RemoteMessage remoteMessage) async {
// handle message
}
- If you have custom Huawei Messaging integration, please see usage below.
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);
}
});
- In order to use the widget URL callback, add these methods into AppDelegate class.
// Required code block to handle widget URL's in Flutter
func shouldHandleOpen(_ url: URL!, for object: NetmeraPushObject!) -> Bool {
return false
}
func handleOpen(_ url: URL!, for object: NetmeraPushObject!) {
FNetmera.handleOpen(url, for: object)
}
Calling Dart methods #
Update User Example
updateUser() {
NetmeraUser user = new NetmeraUser();
user.setUserId(userController.text);
user.setName(nameController.text);
user.setSurname(surnameController.text);
user.setEmail(emailController.text);
user.setMsisdn(msisdnController.text);
user.setGender(int.parse(_selectedGender));
// User update async
Netmera.updateUser(user);
// User update sync
Netmera.updateUser(user).then((value) {
print('User updated');
}).catchError((error) {
print('User update failed: $error');
});
}
Sending Event Examples
You can send your events as follows. For more examples, please see the example project.
void sendLoginEvent() {
NetmeraEventLogin loginEvent = new NetmeraEventLogin();
Netmera.sendEvent(loginEvent);
}
void sendRegisterEvent() {
NetmeraEventRegister registerEvent = new NetmeraEventRegister();
Netmera.sendEvent(registerEvent);
}
void sendViewCartEvent() {
NetmeraEventCartView cartViewEvent = new NetmeraEventCartView();
cartViewEvent.setItemCount(3);
cartViewEvent.setSubTotal(15.99);
Netmera.sendEvent(cartViewEvent);
}
Widget URL Callback
In order to use the widget URL callback, use onWidgetUrlTriggered
method as follows.
void _onWidgetUrlTriggered(String url) {
String message = "Widget URL handle by app: " + url;
print(message);
}
Netmera.onWidgetUrlTriggered(_onWidgetUrlTriggered);
Push Notification Permissions
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
});
Netmera Inbox Examples
You can fetch the Netmera inbox as following. For more detailed usage, please see the example project.
getInboxFilter() {
NetmeraInboxFilter inboxFilter = NetmeraInboxFilter();
inboxFilter.setPageSize(2);
inboxFilter.setStatus(Netmera.PUSH_OBJECT_STATUS_UNREAD);
inboxFilter.setIncludeExpiredObjects(true);
inboxFilter.setCategories(null);
return inboxFilter;
}
fetchInbox() async {
Netmera.fetchInbox(getInboxFilter()).then((list) {
debugPrint(list);
}).catchError((error) {
debugPrint(error);
});
}
Netmera Inbox Category Examples
You can fetch the Netmera category as following. For more detailed usage, please see the example project.
getCategoryFilter() {
NetmeraCategoryFilter categoryFilter = NetmeraCategoryFilter();
categoryFilter.setPageSize(2);
categoryFilter.setStatus(Netmera.PUSH_OBJECT_STATUS_UNREAD);
categoryFilter.setIncludeExpiredObjects(true);
return categoryFilter;
}
fetchCategory() async {
Netmera.fetchCategory(getCategoryFilter()).then((list) {
debugPrint(list);
}).catchError((error) {
debugPrint(error);
});
}
Netmera Getting ExternalId (if exists before)
Netmera.getCurrentExternalId()
Please explore example folder in the Netmera SDK library for detailed information.
Netmera Popup Presentation
To enable popup presentation, you need to call the enablePopupPresentation()
method on the page where you want to display the popup.
Note: To show popup on the app start or everywhere in the app, please add this to initState()
method on your main.dart
file.
Netmera.enablePopupPresentation();
Data Start-Stop Transfer
Stop Data Transfer Method
The stopDataTransfer() method is a useful feature that can help users to temporarily pause all requests sent by the SDK to the backend. This can be useful if, for example, the user needs to temporarily halt data transfers due to network issues or other reasons. Once the issue has been resolved, the user can then restart the data transfer using the startDataTransfer() method.
Netmera.stopDataTransfer();
Start Data Transfer Method
The startDataTransfer() method is a complementary feature to the stopDataTransfer() method, which allows users to restart any stopped requests. This can be useful when the user has temporarily paused data transfers and is now ready to resume the transfer. Once the user calls the startDataTransfer() method, the SDK will attempt to resend any requests that were previously stopped.
Netmera.startDataTransfer();
Please explore our example project for detailed information.