> This page is for Applications Protection.

> For clean Markdown of any page, append .md to the page URL.
> For a complete documentation index, see https://docs.humansecurity.com/llms.txt.

# Flutter integration

> **Note**
>
> This guide is relevant for the current Mobile SDK. While we highly recommend using the latest version, if you are using a legacy integration, refer to the [iOS](/applications/ios-how-to-integrate-the-sdk-in-your-application-v3) or [Android](/applications/android-how-to-integrate-the-sdk-in-your-application-v3) documentation.

You can integrate the SDK into a [Flutter](https://flutter.dev/) project. There is no HUMAN Flutter package. Call the native SDK from Dart through a method channel.

## Start the SDK

When starting the SDK, keep the following in mind:

1. **Start the SDK as soon as possible** on the **main thread**. We recommend doing so in the `Application`'s `onCreate` function on Android or the `AppDelegate`'s `didFinishLaunchingWithOptions` function on iOS. If your app sends a URL request to your server before the SDK starts, the request will not include the SDK's HTTP headers. As a result:
   * The

     Enforcer

     may block the request, and
   * The SDK will not be able to present a challenge to the user
2. Create a `HumanManager` that handles calls from Flutter. On Android, register it on the `FlutterEngine`. On iOS, set up the method channel.

Below are example implementations for Android and iOS:

> **Note**
>
> Don't forget to replace `<APP_ID>` with your actual **Application ID**.

#### Android

**`Kotlin (MainApplication.kt)`**

```kotlin title="Kotlin (MainApplication.kt)"
import android.app.Application

class MainApplication: Application() {

    override fun onCreate() {
        super.onCreate()
        HumanManager.start(this)
    }
}
```

**`Kotlin (HumanManager.kt)`**

```kotlin title="Kotlin (HumanManager.kt)"
import android.app.Application
import com.humansecurity.mobile_sdk.HumanSecurity
import com.humansecurity.mobile_sdk.main.policy.HSPolicy
import com.humansecurity.mobile_sdk.main.policy.HSAutomaticInterceptorType
import com.humansecurity.mobile_sdk.main.HSBotDefenderChallengeResult
import io.flutter.plugin.common.MethodCall
import io.flutter.plugin.common.MethodChannel
import org.json.JSONObject

class HumanManager {

    companion object {
        fun start(application: Application) {
            try {
                val policy = HSPolicy()
                policy.automaticInterceptorPolicy.interceptorType = HSAutomaticInterceptorType.NONE
                HumanSecurity.start(application, "<APP_ID>", policy)
            }
            catch (exception: Exception) {
                println("Exception: ${exception.message}")
            }
        }

        fun handleEvent(call: MethodCall, result: MethodChannel.Result) {
            if (call.method == "humanGetHeaders") {
                val json = JSONObject((HumanSecurity.BD.headersForURLRequest("<APP_ID>") as Map<*, *>?))
                result.success(json.toString())
            }
            else if (call.method == "humanHandleResponse") {
                val handled = HumanSecurity.BD.handleResponse(call.arguments!! as String) { challengeResult: HSBotDefenderChallengeResult ->
                    result.success(if (challengeResult == HSBotDefenderChallengeResult.SOLVED) "solved" else "cancelled")
                    null
                }
                if (!handled) {
                    result.success("false")
                }
            }
            else {
                result.notImplemented()
            }
        }
    }
}
```

**`Kotlin (MainActivity.kt)`**

```kotlin title="Kotlin (MainActivity.kt)"
import androidx.annotation.NonNull
import io.flutter.embedding.android.FlutterActivity
import io.flutter.embedding.engine.FlutterEngine
import io.flutter.plugin.common.MethodChannel

class MainActivity: FlutterActivity() {

    override fun configureFlutterEngine(@NonNull flutterEngine: FlutterEngine) {
        super.configureFlutterEngine(flutterEngine)
        MethodChannel(flutterEngine.dartExecutor.binaryMessenger, "com.humansecurity/sdk").setMethodCallHandler {
                call, result ->
            HumanManager.handleEvent(call, result)
        }
    }
}
```

#### iOS

**`Swift (HumanManager.swift)`**

```swift title="Swift (HumanManager.swift)"
import Foundation
import Flutter
import HUMAN

class HumanManager {

    static let shared = HumanManager()

    func start() {
        do {
            let policy = HSPolicy()
            policy.automaticInterceptorPolicy.interceptorType = .none

            try HumanSecurity.start(appId: "<APP_ID>", policy: policy)
        }
        catch {
            print("Error: \(error)")
        }
    }

    func setupChannel(with controller: FlutterViewController) {
        let humanChannel = FlutterMethodChannel(name: "com.humansecurity/sdk", binaryMessenger: controller.binaryMessenger)
        humanChannel.setMethodCallHandler({(call: FlutterMethodCall, result: @escaping FlutterResult) -> Void in
            if call.method == "humanGetHeaders" {
                var json: String?
                do {
                    let headers = HumanSecurity.BD.headersForURLRequest(forAppId: "<APP_ID>")
                    let data = try JSONSerialization.data(withJSONObject: headers)
                    json = String(data: data, encoding: .utf8)
                }
                catch {
                    print("Error: \(error)")
                }
                result(json)
            }
            else if call.method == "humanHandleResponse" {
                if let response = call.arguments as? String, let data = response.data(using: .utf8), let httpURLResponse = HTTPURLResponse(url: URL(string: "https://example.com")!, statusCode: 403, httpVersion: nil, headerFields: nil) {
                    let handled = HumanSecurity.BD.handleResponse(response: httpURLResponse, data: data) { challengeResult in
                        result(challengeResult == .solved ? "solved" : "cancelled")
                    }
                    if handled {
                        return
                    }
                }
                result("false")
            }
            else {
                result("")
            }
        })
    }
}
```

**`Swift (AppDelegate.swift)`**

```swift title="Swift (AppDelegate.swift)"
import UIKit
import Flutter

@UIApplicationMain
@objc class AppDelegate: FlutterAppDelegate {

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

        HumanManager.shared.start()

        let controller : FlutterViewController = window?.rootViewController as! FlutterViewController
        HumanManager.shared.setupChannel(with: controller)

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

In particular, note the following:

1. **Initialization:** We start the SDK as early as possible on the main thread.
2. **Policy configuration:** We create an `HSPolicy` instance and set `HSAutomaticInterceptorPolicy/interceptorType` property to `HSAutomaticInterceptorType/none`. That disables **Automatic Interception**, which lets the SDK manipulate URL requests and handle their responses, but isn't supported in Flutter. If the app loads a HUMAN-protected site in `webview_flutter`, also set `hybridAppPolicy.webRootDomains` and `hybridAppPolicy.supportExternalWebViews = true` before start. There is no HUMAN Flutter package that turns that flag on for you. See [WebView container support](/applications/sdk/v4/webview-container-support) for more information.
3. **Starting the SDK:** We call `HumanSecurity/start(appId:policy:)` with the following parameters:
   * The `Application` instance (Android only)
   * Your

     Application ID

     . If you have multiple IDs, see our [guide](/applications/sdk/v4/getting-started#handle-multiple-application-ids) on how to handle them.
   * The `HSPolicy` object that we configured

## Send your requests through the SDK and check for a blocked request

1. In your Dart code, create a `MethodChannel`.
2. Add the SDK's HTTP headers to the URL request.
3. When a request is blocked, send the block response to the SDK.
4. Handle the challenge’s result. See [handle blocked requests](#handle-blocked-requests) for more information.

Below is an example implementation:

**`Dart`**

```dart title="Dart"
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import '../settings/settings_view.dart';
import 'dart:async';
import 'dart:convert';
import 'package:http/http.dart' as http;

class MyView extends StatelessWidget {

    static const humanPlatform = MethodChannel('com.humansecurity/sdk');

    Future<void> sendUrlRequest() async {
        try {
            final String humanHeaders = await humanPlatform.invokeMethod('humanGetHeaders');
            final Map<String, String> humanHeadersMap = Map.from(json.decode(humanHeaders));
            var url = Uri.https('example.com', '/action');
            var response = await http.get(url, headers: humanHeadersMap);
            if (response.statusCode == 403) {
                final String result = await humanPlatform.invokeMethod('humanHandleResponse', response.body);
                if (result == 'solved') {
                    print("Challenge was solved");
                } else if (result == 'false') {
                    print("Request was not blocked by HUMAN");
                } else if (result == 'cancelled') {
                    print("Challenge was cancelled");
                }
            }
        } on PlatformException catch (exception) {
            print("Exception: '${exception.message}'");
        }
    }
}
```

## Handle blocked requests

When the **Enforcer** blocks a request, it returns a JSON string in the response body with an HTTP status code of `403`, which includes metadata for the SDK. For example:

```json
{
  "vid": "928d7ab3-9cf1-11ee-a624-b802520f369f",
  "uuid": "fd01e6d6-9cf2-11ee-808c-acde48001122",
  "page": "...",
  "appId": "PXj9y4Q8Em",
  "action": "captcha",
  "collectorUrl": "https://collector-pxj9y4q8em.perimeterx.net"
}
```

Your app should pass the whole JSON to the SDK via the `HSBotDefender/handleResponse(response:data:callback:)` function. If not, the SDK won't present a challenge to the user.