# SDK Integration

{% embed url="<https://pub.dev/packages/netmera_flutter_sdk#-readme-tab->" %}
Flutter Package
{% endembed %}

#### Example Project

For a practical example, check out the [**Netmera Flutter Example Project**](https://github.com/Netmera/Netmera-Flutter-Example/tree/master) on GitHub, which shows how to integrate the Flutter SDK.

## 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.

{% file src="/files/w3hxJiViuHHnGVBizccs" %}

## Step 1: Install Flutter <a href="#installation" id="installation"></a>

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:

```yaml
dependencies:
  netmera_flutter_sdk: ^x.x.x
```

2. Install the package using the command:

```bash
$ flutter pub get
```

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

## Step 2: Setup Android <a href="#setup-android-part" id="setup-android-part"></a>

### 1. Netmera Android Onboarding <a href="#create-a-firebase-cloud-messaging-configuration" id="create-a-firebase-cloud-messaging-configuration"></a>

**In Netmera Panel**:

* Navigate to **Developers** > **Netmera Onboarding**.
* Select **Android** and click **Start** to proceed.

<figure><img src="/files/RiJFUO6B2HbE49DWYixW" alt="" width="563"><figcaption></figcaption></figure>

### 2. Create a Firebase Configuration

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

1. Go to the [**Firebase Developers Console**](https://console.firebase.google.com/) 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.

{% @arcade/embed flowId="wWs2Yesf5jfbmH6BBLOc" url="<https://app.arcade.software/share/wWs2Yesf5jfbmH6BBLOc>" %}

### 3. Select a Target SDK <a href="#integrate-sdk" id="integrate-sdk"></a>

Choose the Flutter based on your application framework.

<figure><img src="/files/aXxzHEnzYCDN3UD8LLhq" alt="" width="563"><figcaption></figcaption></figure>

### 4. Integrate and Initialize **Flutter** SDK <a href="#integrate-sdk" id="integrate-sdk"></a>

<figure><img src="https://lh7-us.googleusercontent.com/5bVVUuZBFS3dRDP9UO2_i31L0jF2Obwpwrh9jIULVFCy5avp84ss9Ntu_VPtVEw93p7ZIYbOc4EZBJhG4AiXU_G-UNz7ZOGg0Udsq5mCmASNUxTQlMI4uPHeR5DOjr_3Q7MCH5f-HQaPutsOBkrzPwk" alt="" width="563"><figcaption></figcaption></figure>

{% hint style="warning" %}
**Important Notes:**

* **Do not** use the API key from a **test** **panel** in production.
* **Each panel has a unique API key**, and using the wrong one can result in data misdirection or errors.

**To obtain your SDK API Key:**

1. Go to the Netmera Panel.
2. Navigate to Developer > API > SDK API Key.
3. Copy your SDK API Key from this section.
   {% endhint %}

### 5. Integrate Netmera <a href="#gradle-file-confugration" id="gradle-file-confugration"></a>

1. **Project’s `build.gradle` File**

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

```groovy
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/'}
    }
}
```

2. **App’s `build.gradle` File**

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

```groovy
 dependencies {
 
     implementation 'androidx.core:core:X.X.X'
     
 }
```

3. **At the top of your app’s `build.gradle`, include:**

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

{% hint style="info" %}
**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.
{% endhint %}

### 6. Initialize Netmera <a href="#initialize-netmera-1" id="initialize-netmera-1"></a>

1. **Create the Application Class**&#x20;

* Create an application class that extends `Application`.
* Replace `<YOUR GCM SENDER ID>`, `<YOUR HMS SENDER ID>`, and `<YOUR NETMERA API KEY>` with your actual values.

{% tabs %}
{% tab title="Kotlin" %}

```kotlin
import android.app.Application
import com.netmera.netmera_flutter_sdk.FNetmera
import com.netmera.netmera_flutter_sdk.FNetmeraConfiguration

class MainApplication : Application() {

    override fun onCreate() {
        super.onCreate()

        val fNetmeraConfiguration = FNetmeraConfiguration.Builder()
            .huaweiSenderId(<YOUR HMS SENDER ID>)
            .firebaseSenderId(<YOUR GCM SENDER ID>)
            .apiKey(<YOUR NETMERA API KEY>)
            .logging(true) // Ensure this is set to 'false' before releasing the app to production!
            .build(this)

        FNetmera.initNetmera(fNetmeraConfiguration)
    }
}
```

{% endtab %}

{% tab title="Java" %}

```java
import android.app.Application;
import com.netmera.netmera_flutter_sdk.FNetmera;
import com.netmera.netmera_flutter_sdk.FNetmeraConfiguration;

public class MainApplication extends Application {

    @Override
    public void onCreate() {
        super.onCreate();

        FNetmeraConfiguration fNetmeraConfiguration = new FNetmeraConfiguration.Builder()
            .huaweiSenderId("<YOUR HMS SENDER ID>")
            .firebaseSenderId("<YOUR GCM SENDER ID>")
            .apiKey("<YOUR NETMERA API KEY>")
            .logging(true) // Ensure this is set to 'false' before releasing the app to production!
            .build(this);

        FNetmera.initNetmera(fNetmeraConfiguration);
    }
}
```

{% endtab %}
{% endtabs %}

## Step 3: Setup iOS <a href="#setup-ios-part" id="setup-ios-part"></a>

### 1. Create an Apple Push Notification Certificate

1. Log in to [**developer.apple.com**](https://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.

{% hint style="info" %}
**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.
{% endhint %}

{% hint style="info" %}
**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.
{% endhint %}

#### Creating an APNS .p8 Certificate (Recommended)

{% embed url="<https://youtu.be/dv-5gmaGsAA?si=A4V085fUEWMpTzXi>" %}

#### Creating an APNS .p12 Certificate

{% embed url="<https://youtu.be/R8tva2tpFyU?si=9JPg1b9Rqt6b0ldl>" %}

### **2. Configure Podfile**

Add the following `post_install` block to the end of your Podfile.

```ruby
post_install do |installer|
  installer.pods_project.targets.each do |target|
    if target.name.include?('Swinject')
      target.build_configurations.each do |config|
        config.build_settings['BUILD_LIBRARY_FOR_DISTRIBUTION'] = 'YES'
      end
    end
  end
end
```

### **3. Install Pods**

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

```shellscript
$ pod install
```

### 4. **Add** Netmera-Config.plist <a href="#integrate-sdk-into-your-project" id="integrate-sdk-into-your-project"></a>

Add the \`Netmera-Config.plist\` file to your ios/Runner directory.

```xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "">
<plist version="1.0">
    <dict>
        <key>sdk_params</key>
        <dict>
            <key>api_key</key>
            <string>YOUR-SDK-API-KEY</string>
        </dict>
    </dict>
</plist>
```

If you are using Netmera on-premises, you must add your server URL as the base\_url key inside sdk\_params.

```xml
<key>base_url</key>
<string>YOUR-BASE-URL</string>
```

{% hint style="info" %}
To obtain your **SDK API Key:**

1. Go to the **Netmera Panel**.
2. Navigate to **Developer > API > SDK API Key**.
3. Copy your **SDK API Key** from this section.

Use this key to replace the `YOUR-SDK-API-KEY` placeholder in the sample code.
{% endhint %}

### 5. Configure Xcode Push Notifications Settings <a href="#enable-push-notifications" id="enable-push-notifications"></a>

1. Open your project in Xcode.
2. Navigate to **Signing & Capabilities**.
3. Click **+ Capability** and select **Push Notifications**.
4. Click **+ Capability** and select **Background Modes** then enable **Background fetch** and **Remote notifications** modes.

<figure><img src="/files/esH7V1f7519pDQXvWmyH" alt=""><figcaption></figcaption></figure>

## Step 4. Setup Dart  <a href="#calling-dart-methods" id="calling-dart-methods"></a>

1. You can set your own push callbacks in Dart side as following. These methods are optional.

```dart
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().initialize(
    onPushRegister: _onPushRegister,
    onPushReceive: _onPushReceive,
    onPushDismiss: _onPushDismiss,
    onPushOpen: _onPushOpen,
    onPushButtonClicked: _onPushButtonClicked,
    onCarouselObjectSelected: _onCarouselObjectSelected,
  );
}
```

2\. 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.&#x20;

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.

```dart
// 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());
}
```

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

{% embed url="<https://pub.dev/packages/netmera_flutter_sdk#-readme-tab->" %}


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://user.netmera.com/netmera-developer-guide/platforms/flutter/sdk-integration.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
