Skip to Content
Docs
Get startedPartner API v4Partner API v3Android SDK
v1.0.8

Flutter Bridge

The Flutter integration uses two standard Flutter platform channels. The Dart bridge class wraps both so your Dart code never touches channel mechanics directly.

Channel architecture

ChannelTypeUsed for
ablecredit/wrapper_sdkMethodChannelRequest/response calls – configure, createNewLoanCase, recordAudio, capturePhotos, startLoanFlow, setShowSdkHeader, setSdkToastsEnabled, clearSdkData, etc.
ablecredit/audio_upload_statusEventChannelPush events – upload status for all capture types, loan_created and flow step events from startLoanFlow. Dart accessor: fileUploadStatusStream

All events carry a "type" field. Use it to distinguish event kinds: • audio / family_photos / business_photos / collateral_photos → upload status event from a standalone capture call (also has uniqueId, status, message) • loan_created → emitted by startLoanFlow when the loan is created (has applicationId, loanReference) • flow_<STEP_NAME> → per-step upload status from startLoanFlow (e.g. flow_RECORD_AUDIO)

Step 1 – Full MainActivity.kt bridge

MainActivity.kt
// android/app/src/main/kotlin/<your_package>/MainActivity.kt
package com.example.app

import android.util.Log
import android.widget.Toast
import com.google.gson.Gson
import com.ablecredit.sdk.manager.AbleCredit
import com.ablecredit.sdk.model.constants.AbleCreditErrorCodes
import com.ablecredit.sdk.model.AbleCreditDockedButton
import com.ablecredit.sdk.model.AbleCreditFileStatus
import com.ablecredit.sdk.model.AbleCreditFileUploadListener
import com.ablecredit.sdk.model.AbleCreditFlowConfig
import com.ablecredit.sdk.model.AbleCreditFlowListener
import com.ablecredit.sdk.model.AbleCreditFlowStep
import com.ablecredit.sdk.model.AbleCreditLoanResponse
import com.ablecredit.sdk.model.AbleCreditResult
import io.flutter.embedding.android.FlutterActivity
import io.flutter.embedding.engine.FlutterEngine
import io.flutter.plugin.common.EventChannel
import io.flutter.plugin.common.MethodChannel

class MainActivity : FlutterActivity() {
    private val gson = Gson()
    private val channelName = "ablecredit/wrapper_sdk"
    private val audioStatusChannelName = "ablecredit/audio_upload_status"
    private var audioStatusSink: EventChannel.EventSink? = null
    private var flutterChannel: MethodChannel? = null

    // Holds the pending MethodChannel.Result for the currently open SDK screen so
    // the docked button's onClick can resolve it early (before a terminal upload status)
    // when the user taps "client screen" and the activity needs to finish first.
    private var pendingCaptureResult: MethodChannel.Result? = null

    override fun onResume() {
        super.onResume()
        // If MainActivity regains focus while a pendingCaptureResult is still set, it means the
        // SDK screen was dismissed via back press (not via docked button or terminal upload status).
        // Resolve it with CANCELLED so Flutter's awaiting call unblocks.
        val pending = pendingCaptureResult
        if (pending != null) {
            pendingCaptureResult = null
            pending.success(mapOf("success" to false, "status" to AbleCreditFileStatus.CANCELLED.name))
        }
    }

    override fun configureFlutterEngine(flutterEngine: FlutterEngine) {
        super.configureFlutterEngine(flutterEngine)

        EventChannel(flutterEngine.dartExecutor.binaryMessenger, audioStatusChannelName)
            .setStreamHandler(object : EventChannel.StreamHandler {
                override fun onListen(arguments: Any?, events: EventChannel.EventSink?) {
                    audioStatusSink = events
                }
                override fun onCancel(arguments: Any?) { audioStatusSink = null }
            })

        val channel = MethodChannel(flutterEngine.dartExecutor.binaryMessenger, channelName)
        flutterChannel = channel
        channel.setMethodCallHandler { call, result ->
            when (call.method) {
                "configure" -> {
                    val sdkKey   = call.argument<String>("sdkKey").orEmpty()
                    val tenantId = call.argument<String>("tenantId").orEmpty()
                    val userId   = call.argument<String>("userId").orEmpty()
                    val baseUrl  = call.argument<String>("baseUrl").orEmpty()
                    val branchId = call.argument<String>("branchId")?.takeIf { it.isNotBlank() }
                    Thread {
                        val configResult = AbleCredit.configure(this, sdkKey, tenantId, userId, baseUrl, branchId)
                        runOnUiThread {
                            when (configResult) {
                                is AbleCreditResult.Success ->
                                    result.success(mapOf("success" to true, "message" to "SDK configured"))
                                is AbleCreditResult.Failure -> {
                                    if (configResult.ableCreditErrorCode == AbleCreditErrorCodes.SDK_ALREADY_INITIALIZED) {
                                        result.success(mapOf("success" to true, "message" to "SDK configured"))
                                    } else {
                                        result.success(mapOf(
                                            "success" to false,
                                            "message" to configResult.message,
                                            "code"    to configResult.ableCreditErrorCode.toString()
                                        ))
                                    }
                                }
                            }
                        }
                    }.start()
                }
                "createNewLoanCase" -> {
                    val payload = call.argument<Map<String, Any?>>("payload") ?: emptyMap()
                    AbleCredit.createNewLoanCase(this, payload) { sdkResult ->
                        result.success(serializeLoanResult(sdkResult))
                    }
                }
                "getLoanById" -> {
                    val applicationId = call.argument<String>("applicationId").orEmpty()
                    AbleCredit.getLoanById(this, applicationId) { sdkResult ->
                        result.success(serializeLoanResult(sdkResult))
                    }
                }
                "getLoanByReference" -> {
                    val loanReference = call.argument<String>("loanReference").orEmpty()
                    AbleCredit.getLoanByReference(this, loanReference) { sdkResult ->
                        result.success(serializeLoanResult(sdkResult))
                    }
                }
                "requestReportGeneration" -> {
                    val loanApplicationId = call.argument<String>("loanApplicationId").orEmpty()
                    AbleCredit.requestReportGeneration(this, loanApplicationId) { sdkResult ->
                        when (sdkResult) {
                            is AbleCreditResult.Success ->
                                result.success(mapOf("success" to true, "message" to sdkResult.message))
                            is AbleCreditResult.Failure ->
                                result.success(mapOf(
                                    "success" to false,
                                    "message" to sdkResult.message,
                                    "code"    to sdkResult.ableCreditErrorCode.toString()
                                ))
                        }
                    }
                }
                "viewLoanApplications" -> {
                    result.success(mapOf("success" to false, "message" to "viewLoanApplications is not supported in this SDK version"))
                }
                "recordAudio" -> {
                    val loanApplicationId = call.argument<String>("loanApplicationId")
                    val dockedButton = buildDockedButton(call.argument("nextStep"), call.argument("nextStepLabel"), loanApplicationId, call.argument("transition"))
                    AbleCredit.recordAudio(
                        context = this,
                        loanApplicationId = loanApplicationId,
                        listener = captureListener("audio", result),
                        dockedButton = dockedButton,
                    )
                }
                "captureFamilyPhotos" -> {
                    val loanApplicationId = call.argument<String>("loanApplicationId")
                    val dockedButton = buildDockedButton(call.argument("nextStep"), call.argument("nextStepLabel"), loanApplicationId, call.argument("transition"))
                    AbleCredit.captureFamilyPhotos(this, loanApplicationId, captureListener("family_photos", result), dockedButton)
                }
                "captureBusinessPhotos" -> {
                    val loanApplicationId = call.argument<String>("loanApplicationId")
                    val dockedButton = buildDockedButton(call.argument("nextStep"), call.argument("nextStepLabel"), loanApplicationId, call.argument("transition"))
                    AbleCredit.captureBusinessPhotos(this, loanApplicationId, captureListener("business_photos", result), dockedButton)
                }
                "captureCollateralPhotos" -> {
                    val loanApplicationId = call.argument<String>("loanApplicationId")
                    val dockedButton = buildDockedButton(call.argument("nextStep"), call.argument("nextStepLabel"), loanApplicationId, call.argument("transition"))
                    AbleCredit.captureCollateralPhotos(this, loanApplicationId, captureListener("collateral_photos", result), dockedButton)
                }
                "startLoanFlow" -> {
                    val stepNames          = call.argument<List<String>>("steps") ?: emptyList()
                    val useExistingLoan    = call.argument<Boolean>("useExistingLoan") ?: false
                    val existingLoanRef    = call.argument<String>("existingLoanApplicationId")
                    val payload            = call.argument<Map<String, Any?>>("payload") ?: emptyMap()

                    val steps = stepNames.mapNotNull { name ->
                        runCatching { AbleCreditFlowStep.valueOf(name) }.getOrNull()
                    }
                    if (steps.isEmpty()) {
                        result.success(mapOf("success" to false, "message" to "No valid flow steps provided"))
                        return@setMethodCallHandler
                    }

                    val flowListener = object : AbleCreditFlowListener {
                        override fun onLoanCreated(applicationId: String, response: AbleCreditLoanResponse) {
                            val loanRef = try { response.data?.application?.loan_reference.orEmpty() } catch (_: Exception) { "" }
                            runOnUiThread {
                                audioStatusSink?.success(mapOf(
                                    "type"          to "loan_created",
                                    "applicationId" to applicationId,
                                    "loanReference" to loanRef
                                ))
                            }
                        }
                        override fun onFileStatusChanged(step: AbleCreditFlowStep, uniqueId: String, status: AbleCreditFileStatus, message: String?) {
                            audioStatusSink?.success(mapOf(
                                "type"     to "flow_${step.name}",
                                "uniqueId" to uniqueId,
                                "status"   to status.name,
                                "message"  to message
                            ))
                        }
                        override fun onFlowCompleted(applicationId: String) {
                            Log.d("AbleCredit", "Flow completed: applicationId=$applicationId")
                        }
                        override fun onFlowFailed(step: AbleCreditFlowStep, error: AbleCreditResult.Failure) {
                            Log.e("AbleCredit", "Flow failed at step=$step: ${error.message}")
                        }
                        override fun onStepCompleted(step: AbleCreditFlowStep) {
                            Log.d("AbleCredit", "Flow step completed: $step")
                        }
                    }

                    try {
                        val config = if (useExistingLoan) {
                            val existingSteps = steps.filter { it != AbleCreditFlowStep.CREATE_LOAN_CASE }
                            AbleCreditFlowConfig.Builder()
                                .steps(*existingSteps.toTypedArray())
                                .listener(flowListener)
                                .withExistingLoan(existingLoanRef.orEmpty())
                        } else {
                            if (!steps.contains(AbleCreditFlowStep.CREATE_LOAN_CASE)) {
                                result.success(mapOf(
                                    "success" to false,
                                    "message" to "\"Create loan case\" is not enabled in Profile → Flow config. Enable it or use Existing loan mode."
                                ))
                                return@setMethodCallHandler
                            }
                            val newSteps = mutableListOf(AbleCreditFlowStep.CREATE_LOAN_CASE)
                            newSteps.addAll(steps.filter { it != AbleCreditFlowStep.CREATE_LOAN_CASE })
                            AbleCreditFlowConfig.Builder()
                                .steps(*newSteps.toTypedArray())
                                .listener(flowListener)
                                .withNewLoan(payload)
                        }
                        AbleCredit.startLoanFlow(this, config)
                        result.success(mapOf("success" to true))
                    } catch (e: IllegalArgumentException) {
                        result.success(mapOf("success" to false, "message" to e.message))
                    }
                }
                "setShowSdkHeader" -> {
                    val show = call.argument<Boolean>("show") ?: true
                    AbleCredit.setShowSdkHeader(show)
                    result.success(mapOf("success" to true))
                }
                "setSdkToastsEnabled" -> {
                    val enabled = call.argument<Boolean>("enabled") ?: true
                    AbleCredit.setSdkToastsEnabled(enabled)
                    result.success(mapOf("success" to true))
                }
                "clearSdkData" -> {
                    AbleCredit.clearSdkData { sdkResult ->
                        when (sdkResult) {
                            is AbleCreditResult.Success -> result.success(mapOf("success" to true))
                            is AbleCreditResult.Failure -> result.success(mapOf("success" to false, "message" to sdkResult.message))
                        }
                    }
                }
                else -> result.notImplemented()
            }
        }
    }

    // Builds a docked button for the current SDK screen.
    // nextStep null → no docked button (last step).
    // transition "direct" → button launches nextStep SDK screen directly from native.
    // transition "clientScreen" → button resolves the pending Flutter result with
    //   {dockedButton:true} and finishes the SDK activity so Flutter comes to the foreground.
    private fun buildDockedButton(
        nextStep: String?,
        nextStepLabel: String?,
        loanApplicationId: String?,
        transition: String?,
    ): AbleCreditDockedButton? {
        if (nextStep == null) return null
        val label = if (nextStepLabel != null) "$nextStepLabel →" else "Next →"

        return when (transition) {
            "clientScreen" -> AbleCreditDockedButton(
                label = "Next: client screen →",
                onClick = { ctx ->
                    val pending = pendingCaptureResult
                    pendingCaptureResult = null
                    pending?.success(mapOf(
                        "success"       to true,
                        "status"        to "DOCKED_BUTTON",
                        "nextStep"      to nextStep,
                        "nextStepLabel" to (nextStepLabel ?: nextStep),
                    ))
                    if (ctx is android.app.Activity) ctx.finish()
                }
            )
            else -> AbleCreditDockedButton(label = label, onClick = { ctx ->
                when (nextStep) {
                    "recordAudio"            -> AbleCredit.recordAudio(ctx, loanApplicationId)
                    "captureBusinessPhotos"  -> AbleCredit.captureBusinessPhotos(ctx, loanApplicationId)
                    "captureFamilyPhotos"    -> AbleCredit.captureFamilyPhotos(ctx, loanApplicationId)
                    "captureCollateralPhotos"-> AbleCredit.captureCollateralPhotos(ctx, loanApplicationId)
                    "generateReport"         -> {
                        if (!loanApplicationId.isNullOrBlank()) {
                            AbleCredit.requestReportGeneration(ctx, loanApplicationId) { _ -> }
                        }
                    }
                }
            })
        }
    }

    // Returns a listener that resolves Flutter's result exactly once on a terminal status.
    // Also registers result as pendingCaptureResult so the clientScreen docked button
    // can resolve it early when the user taps to show the client screen.
    private fun captureListener(type: String, result: MethodChannel.Result): AbleCreditFileUploadListener {
        pendingCaptureResult = result
        var resolved = false
        return object : AbleCreditFileUploadListener {
            override fun onStatusChanged(uniqueId: String, status: AbleCreditFileStatus, message: String?) {
                audioStatusSink?.success(mapOf(
                    "type"     to type,
                    "uniqueId" to uniqueId,
                    "status"   to status.name,
                    "message"  to message,
                ))
                val isTerminal = status == AbleCreditFileStatus.UPLOADED
                    || status == AbleCreditFileStatus.FAILED
                    || status == AbleCreditFileStatus.CANCELLED
                if (isTerminal && !resolved) {
                    if (pendingCaptureResult === result) {
                        pendingCaptureResult = null
                        resolved = true
                        runOnUiThread {
                            result.success(mapOf("success" to (status == AbleCreditFileStatus.UPLOADED), "status" to status.name))
                        }
                    }
                }
            }
        }
    }

    private fun serializeLoanResult(sdkResult: AbleCreditResult<AbleCreditLoanResponse>): Map<String, Any?> {
        return when (sdkResult) {
            is AbleCreditResult.Success -> {
                val loan = sdkResult.data
                val applicationId = try { loan?.data?.application?._id.orEmpty() } catch (_: Exception) { "" }
                mapOf(
                    "success"       to true,
                    "message"       to (sdkResult.message ?: loan?.message ?: loan?.msg ?: "OK"),
                    "applicationId" to applicationId,
                    "data"          to loan?.let { gson.fromJson(gson.toJson(it), Map::class.java) },
                )
            }
            is AbleCreditResult.Failure -> mapOf(
                "success" to false,
                "message" to sdkResult.message,
                "code"    to sdkResult.ableCreditErrorCode.toString(),
            )
        }
    }
}

Step 2 – Full Dart bridge file

lib/ablecredit_sdk_bridge.dart
// lib/ablecredit_sdk_bridge.dart
import 'package:flutter/services.dart';

class AbleCreditSdkBridge {
  static const MethodChannel _channel = MethodChannel('ablecredit/wrapper_sdk');
  static const EventChannel _audioUploadStatusChannel = EventChannel('ablecredit/audio_upload_status');

  static Future<Map<String, dynamic>> configure({
    required String sdkKey,
    required String tenantId,
    required String userId,
    required String baseUrl,
    String branchId = '',
  }) async {
    final args = <String, dynamic>{
      'sdkKey': sdkKey,
      'tenantId': tenantId,
      'userId': userId,
      'baseUrl': baseUrl,
    };
    if (branchId.trim().isNotEmpty) args['branchId'] = branchId.trim();
    final dynamic res = await _channel.invokeMethod('configure', args);
    return Map<String, dynamic>.from(res as Map);
  }

  static Future<Map<String, dynamic>> createNewLoanCase(Map<String, dynamic> payload) async {
    final dynamic res = await _channel.invokeMethod('createNewLoanCase', {
      'payload': payload,
    });
    return Map<String, dynamic>.from(res as Map);
  }

  static Future<Map<String, dynamic>> getLoanById(String applicationId) async {
    final dynamic res = await _channel.invokeMethod('getLoanById', {
      'applicationId': applicationId,
    });
    return Map<String, dynamic>.from(res as Map);
  }

  static Future<Map<String, dynamic>> getLoanByReference(String loanReference) async {
    final dynamic res = await _channel.invokeMethod('getLoanByReference', {
      'loanReference': loanReference,
    });
    return Map<String, dynamic>.from(res as Map);
  }

  static Future<Map<String, dynamic>> requestReportGeneration(String loanApplicationId) async {
    final dynamic res = await _channel.invokeMethod('requestReportGeneration', {
      'loanApplicationId': loanApplicationId,
    });
    return Map<String, dynamic>.from(res as Map);
  }

  static Future<Map<String, dynamic>> viewLoanApplications() async {
    final dynamic res = await _channel.invokeMethod('viewLoanApplications');
    return Map<String, dynamic>.from(res as Map);
  }

  static Future<Map<String, dynamic>> clearSdkData() async {
    final dynamic res = await _channel.invokeMethod('clearSdkData');
    return Map<String, dynamic>.from(res as Map);
  }

  // [loanApplicationId] is the server-generated _id returned by createNewLoanCase.
  // [nextStep] is the method name of the next capture step (e.g. 'captureBusinessPhotos').
  // [nextStepLabel] is the human-readable label shown on the docked button.
  // [transition] either 'direct' (button launches next SDK screen) or
  // 'clientScreen' (button triggers Flutter to push a client screen first).
  static Future<Map<String, dynamic>> recordAudio({
    String? loanApplicationId,
    String? nextStep,
    String? nextStepLabel,
    String? transition,
  }) async {
    final args = <String, dynamic>{};
    final id = loanApplicationId?.trim();
    if (id != null && id.isNotEmpty) args['loanApplicationId'] = id;
    if (nextStep != null) args['nextStep'] = nextStep;
    if (nextStepLabel != null) args['nextStepLabel'] = nextStepLabel;
    if (transition != null) args['transition'] = transition;
    final dynamic res = await _channel.invokeMethod('recordAudio', args);
    return Map<String, dynamic>.from(res as Map);
  }

  static Future<Map<String, dynamic>> captureFamilyPhotos({
    String? loanApplicationId,
    String? nextStep,
    String? nextStepLabel,
    String? transition,
  }) async {
    final args = <String, dynamic>{};
    final id = loanApplicationId?.trim();
    if (id != null && id.isNotEmpty) args['loanApplicationId'] = id;
    if (nextStep != null) args['nextStep'] = nextStep;
    if (nextStepLabel != null) args['nextStepLabel'] = nextStepLabel;
    if (transition != null) args['transition'] = transition;
    final dynamic res = await _channel.invokeMethod('captureFamilyPhotos', args);
    return Map<String, dynamic>.from(res as Map);
  }

  static Future<Map<String, dynamic>> captureBusinessPhotos({
    String? loanApplicationId,
    String? nextStep,
    String? nextStepLabel,
    String? transition,
  }) async {
    final args = <String, dynamic>{};
    final id = loanApplicationId?.trim();
    if (id != null && id.isNotEmpty) args['loanApplicationId'] = id;
    if (nextStep != null) args['nextStep'] = nextStep;
    if (nextStepLabel != null) args['nextStepLabel'] = nextStepLabel;
    if (transition != null) args['transition'] = transition;
    final dynamic res = await _channel.invokeMethod('captureBusinessPhotos', args);
    return Map<String, dynamic>.from(res as Map);
  }

  static Future<Map<String, dynamic>> captureCollateralPhotos({
    String? loanApplicationId,
    String? nextStep,
    String? nextStepLabel,
    String? transition,
  }) async {
    final args = <String, dynamic>{};
    final id = loanApplicationId?.trim();
    if (id != null && id.isNotEmpty) args['loanApplicationId'] = id;
    if (nextStep != null) args['nextStep'] = nextStep;
    if (nextStepLabel != null) args['nextStepLabel'] = nextStepLabel;
    if (transition != null) args['transition'] = transition;
    final dynamic res = await _channel.invokeMethod('captureCollateralPhotos', args);
    return Map<String, dynamic>.from(res as Map);
  }

  // Starts the orchestrator loan flow: runs the given capture steps in order.
  // steps are AbleCreditFlowStep enum names (RECORD_AUDIO, CAPTURE_BUSINESS_PHOTOS,
  // CAPTURE_FAMILY_PHOTOS, CAPTURE_COLLATERAL_PHOTOS).
  // When useExistingLoan is true, existingLoanApplicationId is required;
  // otherwise payload is used to create a new loan.
  static Future<Map<String, dynamic>> startLoanFlow({
    required List<String> steps,
    required bool useExistingLoan,
    String? existingLoanApplicationId,
    Map<String, dynamic>? payload,
  }) async {
    final args = <String, dynamic>{
      'steps': steps,
      'useExistingLoan': useExistingLoan,
    };
    final ref = existingLoanApplicationId?.trim();
    if (ref != null && ref.isNotEmpty) args['existingLoanApplicationId'] = ref;
    if (payload != null) args['payload'] = payload;
    final dynamic res = await _channel.invokeMethod('startLoanFlow', args);
    return Map<String, dynamic>.from(res as Map);
  }

  // Controls whether the SDK capture screens show their own header row.
  // Default on the SDK side is true. Set to false if the host app provides its own toolbar.
  static Future<void> setShowSdkHeader(bool show) async {
    await _channel.invokeMethod('setShowSdkHeader', {'show': show});
  }

  // Controls whether the SDK shows its own operation result toasts.
  // Default on the SDK side is true. Set to false if the host app shows its own result UI.
  static Future<void> setSdkToastsEnabled(bool enabled) async {
    await _channel.invokeMethod('setSdkToastsEnabled', {'enabled': enabled});
  }

  // Emits upload status events for all media types.
  // Each event contains: type (audio|family_photos|business_photos|collateral_photos|loan_created),
  // uniqueId, status (AbleCreditFileStatus name), message.
  static Stream<Map<String, dynamic>> get fileUploadStatusStream {
    return _audioUploadStatusChannel.receiveBroadcastStream().map(
      (event) => Map<String, dynamic>.from(event as Map),
    );
  }
}

Consuming the event stream

final sub = AbleCreditSdkBridge.fileUploadStatusStream.listen((event) {
  final type = event['type'] as String?;

  switch (type) {
    case 'loan_created':
      // Emitted by startLoanFlow when the loan is created.
      final applicationId = event['applicationId'] as String?;
      final loanRef       = event['loanReference'] as String?;
      debugPrint('loan created => id=$applicationId ref=$loanRef');
      // persist applicationId / loanRef here

    case 'audio':
    case 'family_photos':
    case 'business_photos':
    case 'collateral_photos':
      // Standalone capture call upload status events.
      final uniqueId = event['uniqueId'] as String?;
      final status   = event['status']   as String?;
      debugPrint('upload [$type] => id=$uniqueId status=$status');

    default:
      // flow_RECORD_AUDIO, flow_CAPTURE_BUSINESS_PHOTOS, etc.
      // Per-step upload status from startLoanFlow.
      if (type != null && type.startsWith('flow_')) {
        final uniqueId = event['uniqueId'] as String?;
        final status   = event['status']   as String?;
        debugPrint('flow step [$type] => id=$uniqueId status=$status');
      }
  }
});

// Cancel in dispose()
sub.cancel();

On this page