---
title: Flutter
description: Integrieren Sie die Human Token Journey in Ihre Flutter-App mit Platform Channels — Custom Tabs auf Android und ASWebAuthenticationSession auf iOS.
canonical: https://developer.unico.io/de/human-plugin/integrations/app/flutter
locale: de
generated_by: markdown-export
---

Flutter

Integrieren Sie die Human Token Journey in Ihre Flutter-App mit Platform Channels.

Die Integration verwendet `MethodChannel`, um an `ASWebAuthenticationSession` auf iOS und Custom Tabs auf Android zu delegieren. Es werden keine externen Pakete benötigt.

### Voraussetzungen

- Flutter 3.x oder höher
- Xcode 14+ für iOS
- Android Studio für Android
- Ein eindeutiges URL-Schema für Ihre App (z. B. `myapp`)

### Schritt 1: URL-Schema definieren

Wählen Sie ein eindeutiges Schema (z. B. `myapp`). Dies wird als `callbackUri` beim Erstellen des Prozesses verwendet:

```text
callbackUri: myapp://callback
```

Erstellen Sie den Prozess mit der Human Plugin-API und senden Sie diesen Wert als `callbackUri`. Siehe [Prozess erstellen](/de/human-plugin/api-reference/create-process).

### Schritt 2: Dart-Service erstellen

```dart
// lib/services/unico_service.dart
import 'package:flutter/services.dart';

class UnicoService {
  static const _channel = MethodChannel('unico_plugin');

  Future<String?> openSession(String url) async {
    try {
      final result = await _channel.invokeMethod<String>('openSession', {'url': url});
      if (result != null) {
        final uri = Uri.parse(result);
        return uri.queryParameters['id'];
      }
      return null;
    } on PlatformException {
      return null;
    }
  }
}
```

### Schritt 3: iOS-Plugin implementieren

```swift
// ios/Runner/UnicoPlugin.swift
import Flutter
import AuthenticationServices

class UnicoPlugin: NSObject, FlutterPlugin, ASWebAuthenticationPresentationContextProviding {
    private var session: ASWebAuthenticationSession?

    static func register(with registrar: FlutterPluginRegistrar) {
        let channel = FlutterMethodChannel(name: "unico_plugin", binaryMessenger: registrar.messenger())
        let instance = UnicoPlugin()
        registrar.addMethodCallDelegate(instance, channel: channel)
    }

    func handle(_ call: FlutterMethodCall, result: @escaping FlutterResult) {
        guard call.method == "openSession",
              let args = call.arguments as? [String: Any],
              let urlString = args["url"] as? String,
              let url = URL(string: urlString) else {
            result(FlutterMethodNotImplemented)
            return
        }

        let newSession = ASWebAuthenticationSession(
            url: url,
            callbackURLScheme: "myapp"
        ) { callbackURL, error in
            self.session = nil
            if let callbackURL = callbackURL {
                result(callbackURL.absoluteString)
            } else {
                result(FlutterError(code: "SESSION_ERROR",
                                    message: error?.localizedDescription ?? "Session cancelled",
                                    details: nil))
            }
        }
        newSession.presentationContextProvider = self
        newSession.prefersEphemeralWebBrowserSession = true
        newSession.start()
        session = newSession
    }

    func presentationAnchor(for session: ASWebAuthenticationSession) -> ASPresentationAnchor {
        guard let windowScene = UIApplication.shared.connectedScenes.first as? UIWindowScene,
              let window = windowScene.windows.first else {
            return ASPresentationAnchor()
        }
        return window
    }
}
```

Registrieren Sie in `AppDelegate.swift`:

```swift
UnicoPlugin.register(with: self.registrar(forPlugin: "UnicoPlugin")!)
```

### Schritt 4: Android-Plugin implementieren

Fügen Sie die Abhängigkeit zu `android/app/build.gradle` hinzu:

```groovy
implementation("androidx.browser:browser:1.5.0")
```

```kotlin
// android/app/src/main/kotlin/<your.package>/UnicoPlugin.kt
package com.yourapp

import android.content.Intent
import android.net.Uri
import androidx.browser.customtabs.CustomTabsIntent
import io.flutter.embedding.engine.plugins.FlutterPlugin
import io.flutter.embedding.engine.plugins.activity.ActivityAware
import io.flutter.embedding.engine.plugins.activity.ActivityPluginBinding
import io.flutter.plugin.common.MethodCall
import io.flutter.plugin.common.MethodChannel

class UnicoPlugin : FlutterPlugin, MethodChannel.MethodCallHandler, ActivityAware {
    private var channel: MethodChannel? = null
    private var binding: ActivityPluginBinding? = null
    private var pendingResult: MethodChannel.Result? = null

    override fun onAttachedToEngine(flutterBinding: FlutterPlugin.FlutterPluginBinding) {
        channel = MethodChannel(flutterBinding.binaryMessenger, "unico_plugin")
        channel?.setMethodCallHandler(this)
    }

    override fun onMethodCall(call: MethodCall, result: MethodChannel.Result) {
        if (call.method == "openSession") {
            val url = call.argument<String>("url") ?: return result.error("MISSING_URL", "URL is required", null)
            pendingResult = result
            val activity = binding?.activity ?: return result.error("NO_ACTIVITY", "No activity", null)
            CustomTabsIntent.Builder().build().launchUrl(activity, Uri.parse(url))
        } else {
            result.notImplemented()
        }
    }

    fun handleRedirect(uri: Uri) {
        if (uri.scheme == "myapp") {
            pendingResult?.success(uri.toString())
            pendingResult = null
        }
    }

    override fun onAttachedToActivity(binding: ActivityPluginBinding) { this.binding = binding }
    override fun onDetachedFromActivity() { binding = null }
    override fun onReattachedToActivityForConfigChanges(binding: ActivityPluginBinding) { this.binding = binding }
    override fun onDetachedFromActivityForConfigChanges() { binding = null }
    override fun onDetachedFromEngine(binding: FlutterPlugin.FlutterPluginBinding) { channel = null }
}
```

Registrieren Sie in `MainActivity.kt` und behandeln Sie Weiterleitungen:

```kotlin
override fun configureFlutterEngine(flutterEngine: FlutterEngine) {
    super.configureFlutterEngine(flutterEngine)
    flutterEngine.plugins.add(UnicoPlugin())
}

override fun onNewIntent(intent: Intent) {
    super.onNewIntent(intent)
    intent.data?.let { uri ->
        if (uri.scheme == "myapp") {
            val plugin = flutterEngine?.plugins?.get(UnicoPlugin::class.java) as? UnicoPlugin
            plugin?.handleRedirect(uri)
        }
    }
}
```

### Schritt 5: URL-Schemata konfigurieren

- iOS
- Android

Fügen Sie zu `Info.plist` hinzu:

```xml
<key>CFBundleURLTypes</key>
<array>
    <dict>
        <key>CFBundleURLSchemes</key>
        <array>
            <string>myapp</string>
        </array>
    </dict>
</array>
```

Fügen Sie zu `AndroidManifest.xml` innerhalb Ihrer Haupt-`<activity>` hinzu:

```xml
<intent-filter>
    <action android:name="android.intent.action.VIEW" />
    <category android:name="android.intent.category.DEFAULT" />
    <category android:name="android.intent.category.BROWSABLE" />
    <data android:scheme="myapp" android:host="callback" />
</intent-filter>
```

### Schritt 6: Journey starten

```dart
final unicoService = UnicoService();
final processId = await unicoService.openSession(processLink);

if (processId != null) {
  // Journey completed — send processId to your backend via Get Process
} else {
  // User canceled
}
```

### Dateiübersicht

| Datei | Zweck |
| --- | --- |
| `lib/services/unico_service.dart` | Dart-MethodChannel-Service |
| `ios/Runner/UnicoPlugin.swift` | iOS — ASWebAuthenticationSession |
| `ios/Runner/AppDelegate.swift` | Plugin-Registrierung |
| `android/.../UnicoPlugin.kt` | Android — Custom Tabs |
| `android/.../MainActivity.kt` | Plugin-Registrierung + Weiterleitungsbehandlung |
| `Info.plist` | iOS-URL-Schema |
| `AndroidManifest.xml` | Android-Intent-Filter |

Zuletzt aktualisiert am **23. Nov. 2026**