> For the complete documentation index, see [llms.txt](https://docs.caf.io/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://docs.caf.io/caf-sdk/caf-sdk-pt-br/flutter/migrating-from-cafsdk.md).

# Migrando do CafSdk

Migre um app Flutter da API sequencial CafSdk para o Certta DevX no caf\_sdk 2.4.0. Compare configuração, inicialização do módulo e tratamento de eventos.

{% hint style="warning" %}
Este guia aborda **caf\_sdk 2.4.0** e superiores (Certta DevX). Para a versão anterior `CafSdk` fluxo sequencial, consulte a [documentação legada](https://docs.caf.io/caf-sdk/flutter/getting-started-with-the-sdk).
{% endhint %}

A partir de **caf\_sdk 2.4.0**, **Certta DevX** (`CerttaSdk`) é a API recomendada para novas integrações. A API sequencial `CafSdk` API continua disponível no mesmo pacote. Os `initializeCafSdk` fluxos existentes continuam funcionando.

Esta página mapeia a API sequencial legada para módulos independentes `open()` chamadas.

## Comparação de APIs

| Área                    | CafSdk (legado)                                                                      | Certta DevX (2.4.0+)                                                |
| ----------------------- | ------------------------------------------------------------------------------------ | ------------------------------------------------------------------- |
| Importação              | `package:caf_sdk/caf_sdk.dart`                                                       | `package:caf_sdk/certta_sdk.dart`                                   |
| Ponto de entrada        | `CafSdk()`                                                                           | `CerttaSdk()`                                                       |
| Sessão                  | `CafSdkConfiguration` + `initializeCafSdk(...)`                                      | `configureSdk(CerttaConfiguration)`                                 |
| Ordem dos módulos       | `presentationOrder` executa Face Liveness e Document Detector em uma única sequência | Cada módulo é aberto independentemente                              |
| Inicialização           | Uma `initializeCafSdk` inicia todo o pipeline                                        | `liveness.open`, `documentDetector.open`, `documentDetectorUi.open` |
| Eventos                 | Único `eventStream` de `CafResponse`                                                 | Streams por módulo + `logStream`                                    |
| Identificador da pessoa | `personId`                                                                           | `userId`                                                            |
| Flag de segurança       | `CafSdkBuilderConfiguration.enableSecurityModule`                                    | `CerttaConfiguration.securityEnabled`                               |
| Cores                   | `CafSdkBuilderConfiguration.colorConfiguration`                                      | `CerttaConfiguration.colorConfiguration`                            |

Seleção de módulos (`caf-modules-config.json`), repositórios Maven, CocoaPods, permissões e ProGuard **não mudam**. Siga o [Guia de Instalação](/caf-sdk/caf-sdk-pt-br/flutter/installation-guide.md).

## 1. Configure a sessão uma vez

```dart
// Antes (CafSdk)
final cafSdk = CafSdk();
await cafSdk.initializeCafSdk(
  cafSdkConfiguration: CafSdkConfiguration(
    mobileToken: 'token',
    personId: 'personId',
    environment: CafEnvironment.prod,
    configuration: CafSdkBuilderConfiguration(
      presentationOrder: [
        CafModuleType.faceLiveness,
        CafModuleType.documentDetector,
      ],
      enableSecurityModule: true,
    ),
  ),
  faceLivenessConfiguration: faceLivenessConfig,
  documentDetectorConfiguration: documentDetectorConfig,
);

// Depois (Certta)
import 'package:flutter/services.dart';

final certta = CerttaSdk();
try {
  await certta.configureSdk(
    const CerttaConfiguration(
      mobileToken: 'token',
      userId: 'personId',
      environment: CafEnvironment.prod,
      securityEnabled: true,
    ),
  );
} on PlatformException catch (e) {
  // Trate BRIDGE_EXCEPTION
}
```

Depois `configureSdk`, atualize as credenciais sem reconstruir a configuração completa:

```dart
try {
  await certta.updateUserId('novo-id-do-usuario');
  await certta.updateMobileToken('novo-jwt-token');
} on PlatformException catch (e) {
  // Trate BRIDGE_EXCEPTION
}
```

## 2. Abra um módulo por vez

Não há `presentationOrder` na Certta. Inicie Face Liveness ou Document Detector quando o fluxo do seu produto precisar.

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

// Vivacidade facial
try {
  await certta.liveness.open(
    const CerttaLivenessConfiguration(
      maxRetryAttempts: 3,
      faceAuthEnabled: false,
      showLoading: true,
      useFaceLivenessUi: true,
    ),
  );
} on PlatformException catch (e) {
  // Trate BRIDGE_EXCEPTION
}

// Detector de documentos (sem interface)
try {
  await certta.documentDetector.open(
    CerttaDocumentDetectorConfiguration(
      flow: [
        CafDocumentDetectorFlow(document: CafDocument.rgFront),
        CafDocumentDetectorFlow(document: CafDocument.rgBack),
      ],
    ),
  );
} on PlatformException catch (e) {
  // Trate BRIDGE_EXCEPTION
}

// Detector de documentos (interface)
try {
  await certta.documentDetectorUi.open(
    CerttaDocumentDetectorUiConfiguration(
      flow: [CafDocumentDetectorFlow(document: CafDocument.rgFront)],
    ),
  );
} on PlatformException catch (e) {
  // Trate BRIDGE_EXCEPTION
}
```

| Configuração legada do módulo        | Inicialização da Certta                                    |
| ------------------------------------ | ---------------------------------------------------------- |
| `CafFaceLivenessConfiguration`       | `CerttaLivenessConfiguration` (`useFaceLivenessUi: false`) |
| `CafFaceLivenessUIConfiguration`     | `CerttaLivenessConfiguration` (`useFaceLivenessUi: true`)  |
| `CafDocumentDetectorConfiguration`   | `CerttaDocumentDetectorConfiguration`                      |
| `CafDocumentDetectorUIConfiguration` | `CerttaDocumentDetectorUiConfiguration`                    |

A configuração de vivacidade da Certta é um conjunto menor: `maxRetryAttempts`, `faceAuthEnabled`, `showLoading`, `useFaceLivenessUi`, e `payFaceDebugMode` (iOS). URLs de proxy, certificados e campos da tela de instruções do Face Liveness de `CafFaceLivenessConfiguration` não fazem parte do objeto de configuração da Certta.

## 3. Ouça eventos tipados do módulo

```dart
// Antes — um stream, CafResponse
cafSdk.eventStream.listen((event) {
  if (event.success != null) { /* moduleName + signedResponse */ }
  if (event.failure != null) { /* CafFailureType */ }
  if (event.error != null) { /* CafErrorType */ }
  if (event.cancelled) { /* usuário cancelou */ }
});

// Depois — assine por módulo (antes de abrir)
certta.liveness.eventStream.listen((event) {
  if (event.success != null) { /* JWT in event.success!.response */ }
  if (event.failed != null) { /* CerttaLivenessFailure */ }
  if (event.error != null) { /* CerttaError */ }
});

certta.documentDetector.eventStream.listen((event) {
  if (event.success != null) { /* JWT */ }
  if (event.error != null) { /* CerttaError */ }
});

certta.logStream.listen((log) {
  print('${log.level}: ${log.message}');
});
```

| CafSdk `CafResponse`     | Equivalente na Certta                                      |
| ------------------------ | ---------------------------------------------------------- |
| `success.signedResponse` | `event.success.response`                                   |
| `success.moduleName`     | Implícito pelo stream que recebeu o evento                 |
| `failure`                | `CerttaLivenessEvent.failed` (`CerttaLivenessFailure`)     |
| `error`                  | `event.error` (`CerttaError`)                              |
| `cancelled`              | Exposto como `CerttaError` (`cancelled` / tipo semelhante) |
| `log`                    | `CerttaSdk.logStream`                                      |
| `loading` / `loaded`     | Não encaminhado nos streams do módulo Certta               |

As rejeições do mapeador de bridge lançam `PlatformException` com `CerttaErrorCode.bridgeException` (`BRIDGE_EXCEPTION`) em vez de aparecer apenas em `eventStream`.

## 4. Pipelines sequenciais

Se você usou `presentationOrder`, telas de transição (`enableTransitionScreens`), ou `waitForAllServices` Com o CafSdk, o mesmo fluxo de produto pode ser construído com o Certta DevX: configure a sessão uma vez e, em seguida, encadeie chamadas de módulo `open()` chamadas a partir da lógica do seu app (por exemplo, iniciar Face Liveness quando o Document Detector emitir `success` em `eventStream`).

A versão sequencial `CafSdk` API continua disponível em `package:caf_sdk/caf_sdk.dart` e está documentada em [Guia de início rápido legado](/caf-sdk/caf-sdk-pt-br/flutter/getting-started-with-the-sdk.md). Ambas as APIs são compatíveis e cobrem necessidades de integração equivalentes — prefira a Certta DevX para novos desenvolvimentos e ao migrar apps existentes.

## Próximos passos

{% content-ref url="/pages/d82530ac6e7f99d44e236a0f308e73c6cf5d0223" %}
[Guia de Instalação](/caf-sdk/caf-sdk-pt-br/flutter/installation-guide.md)
{% endcontent-ref %}

{% content-ref url="/pages/27eb4d45188aecea60770da2e140e2268d279a61" %}
[Face Liveness](/caf-sdk/caf-sdk-pt-br/flutter/face-liveness.md)
{% endcontent-ref %}

{% content-ref url="/pages/f9c21688ee93566696de0e14a6be2ee1e3252082" %}
[Document Detector](/caf-sdk/caf-sdk-pt-br/flutter/document-detector.md)
{% endcontent-ref %}


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

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

Perform an HTTP GET request on the following URL with the `ask` and `goal` query parameters:

```
GET https://docs.caf.io/caf-sdk/caf-sdk-pt-br/flutter/migrating-from-cafsdk.md?ask=<question>&goal=<user_goal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is what the user is ultimately trying to achieve, the reason they need the answer. Sharing it helps GitBook give you a better, more relevant answer. A goal is most helpful when it describes the outcome the user wants rather than restating the question. For example, with `ask=how do I create an API token`, a goal like `automate deployments from our CI pipeline` lets GitBook tailor the answer to that use case.

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.
