--- title: SDK Flutter --- # SDK Flutter Plugin Flutter construído sobre os SDKs nativos de iOS / Android, expondo um único `CaptchalaClient` em Dart para ambas as plataformas móveis (com suporte a desktop Linux / macOS / Windows via WebView embarcada). ## Demonstração no GitHub ::: tip 📦 [Captcha-La/flutter-demo](https://github.com/Captcha-La/flutter-demo) — exemplo executável completo com cada passo de integração. ::: ## Instalação Adicione o pacote a partir do pub.dev: ```yaml # pubspec.yaml dependencies: captchala: ^1.3.2 http: ^1.2.0 # used by the demo's token-fetch helpers ``` ```bash flutter pub get flutter run # auto-picks the foreground device # or: flutter run -d ``` Para iOS / macOS, o primeiro build executa `pod install` automaticamente. Verifique se `ios/Podfile` declara `platform :ios, '13.0'` (ou superior). ## Início rápido ```dart import 'package:flutter/material.dart'; import 'package:captchala/captchala.dart'; class LoginScreen extends StatefulWidget { const LoginScreen({super.key}); @override State createState() => _LoginScreenState(); } class _LoginScreenState extends State { String _status = 'Tap to verify'; bool _verifying = false; Future _runVerify() async { setState(() { _verifying = true; _status = 'Fetching server_token...'; }); // 1. Fetch a one-shot server_token from YOUR backend. final initialToken = await fetchServerTokenFromYourBackend(); // 2. Build config from your business action. final config = CaptchalaConfig( appKey: 'YOUR_APP_KEY', action: 'login', // login, register, pay, … lang: 'en', // en, zh-CN, zh-TW, ja, ko, ms, vi, id theme: 'light', // 'light' | 'dark' enableVoice: true, enableOfflineMode: true, maskClosable: false, serverToken: initialToken, ); // 3. Initialize, register callbacks, then call verify(). final client = await CaptchalaClient.instance.initialize(config); client.setCallbacks( onSuccess: (r) async { // Send r.passToken to YOUR backend for validation. if (!mounted) return; setState(() { _status = 'OK: ${r.passToken}'; _verifying = false; }); }, onFail: (e) { if (mounted) setState(() { _status = 'fail: ${e.code}'; _verifying = false; }); }, onError: (e) { if (mounted) setState(() { _status = 'error: ${e.code} ${e.message}'; _verifying = false; }); }, onClose: () { if (mounted && _verifying) setState(() { _status = 'closed'; _verifying = false; }); }, onServerTokenExpired: () => fetchServerTokenFromYourBackend(), ); await client.verify(); } @override Widget build(BuildContext context) { return Scaffold( body: Center( child: Column(mainAxisSize: MainAxisSize.min, children: [ ElevatedButton( onPressed: _verifying ? null : _runVerify, child: Text(_verifying ? 'Verifying...' : 'Verify with CAPTCHA'), ), const SizedBox(height: 12), Text(_status, style: const TextStyle(fontFamily: 'monospace')), ]), ), ); } } ``` ## Superfície da API | Símbolo | Função | | --- | --- | | `CaptchalaClient.instance` | Acessor singleton do plugin. | | `CaptchalaConfig(...)` | Record Dart simples: `appKey`, `action`, `lang`, `theme`, `enableVoice`, `enableOfflineMode`, `maskClosable`, `serverToken`. | | `await client.initialize(config)` | Aplica a configuração. Devolve a mesma instância do cliente para permitir encadear `setCallbacks`. | | `setCallbacks(...)` | Registra os callbacks `onSuccess`, `onFail`, `onError`, `onClose`, `onServerTokenExpired`. | | `await client.verify()` | Abre a view nativa do CAPTCHA (Android: Activity sobre o Flutter; iOS: UIViewController sobre o Flutter). | | `CaptchalaResult` | Fornecido a `onSuccess`. Campos: `passToken`, `challengeId`, `ttl`, `isOffline`, `isClientOnly`. | ## Validação no servidor Encaminhe `result.passToken` (ou `result.token`) ao seu backend e valide-o contra a API da CaptchaLa. Nunca exponha `X-App-Secret` em código de cliente. ```bash POST https://apiv1.captcha.la/v1/validate X-App-Key: YOUR_APP_KEY X-App-Secret: YOUR_APP_SECRET Content-Type: application/json { "pass_token": "" } ``` Veja a [Referência da API](/pt-BR/api-reference) para o endpoint completo de validação e o fluxo `X-App-Key` / `X-App-Secret`. ## Solução de problemas - **`pod install` falha no iOS** Em `ios/Podfile` defina `platform :ios, '13.0'` (ou superior). Execute `flutter clean && flutter pub get && cd ios && pod install` depois de trocar a versão do plugin. - **Incompatibilidade de `minSdkVersion` no Android** Aumente `android/app/build.gradle` para `minSdkVersion 21`. O SDK nativo Android recusa compilar abaixo disso. - **Callbacks disparam em um isolate de background** Sempre proteja `setState` com `if (mounted)` antes de mutar o estado da UI dentro de callbacks. A demo embrulha cada callback que atualiza estado com essa verificação. - **Alvos de desktop (Linux / Windows / macOS)** Linux requer GTK3 + WebKitGTK + libcurl. Windows precisa do Runtime Edge WebView2 (Windows 10 1809+). O macOS desktop usa a WebView do sistema automaticamente. ## Requisitos - Flutter 3.10+ / Dart 3.0+ - Android: `minSdkVersion 21` (Android 5.0+) - iOS: 13.0+ com CocoaPods - Desktop (opcional): GTK3 + WebKitGTK no Linux, Runtime WebView2 no Windows 10 1809+