> ## Documentation Index
> Fetch the complete documentation index at: https://docs.crossmint.com/llms.txt
> Use this file to discover all available pages before exploring further.

# Flutter Quickstart

> Let users withdraw stablecoins to their bank account from your Flutter app

In this guide, you will add a withdrawal flow to a Flutter app with the `CrossmintEmbeddedOfframp` component and run a withdrawal in the Staging environment. You will:

* Create an offramp session on your server for the user and the wallet they withdraw from
* Render `CrossmintEmbeddedOfframp` with the session and the user's Crossmint wallet
* Handle the component's events
* Test a withdrawal on staging

The component runs the whole withdrawal inside your app: the user picks, adds, renames or removes a bank account, enters an amount, verifies their identity if the order needs it, reviews the quote and approves the deposit from their wallet.

<Snippet file="offramp-embedded-flow.mdx" />

## Prerequisites

* **Backend**: one server endpoint that creates the session, such as the Express route in this guide.
* **Flutter**: Flutter 3.41.6 or later.

<Snippet file="offramp-embedded-prereqs.mdx" />

* **Crossmint wallet**: an EVM or Solana wallet owned by `userId:<USER_ID>`, where the user ID is the `sub` of your JWT, loaded with its signer as in the [Flutter wallets quickstart](https://docs.crossmint.com/wallets/quickstarts/flutter.md). Set up your authentication as in [Use Your Own Auth Provider](https://docs.crossmint.com/wallets/guides/bring-your-own-auth.md), with `base-sepolia` as the chain. The session takes only `userId:` locators, so email and phone locators do not work.
* **USDC**: testnet USDC in the wallet, from the [Circle faucet](https://faucet.circle.com/).
* **Camera access**: identity verification captures documents with the camera. On iOS, set `NSCameraUsageDescription` in `ios/Runner/Info.plist`. On Android, declare `android.permission.CAMERA` in `AndroidManifest.xml` and request the runtime permission before the user reaches identity verification, for example when `onStatusChange` reports `verifyingIdentity`. The SDK does not request it.

Install the Crossmint Flutter SDK, version 0.9.0 or later, and the `http` package that the example uses to call your backend:

```bash theme={null}
flutter pub add crossmint_flutter http
```

Pass your client-side API key when you run the app:

```bash theme={null}
flutter run --dart-define=CROSSMINT_API_KEY=YOUR_CLIENT_API_KEY
```

### 1. Create the session on your server

A session lets one user make one withdrawal from one wallet. Your backend makes one call, [Create Offramp Session](https://docs.crossmint.com/offramp/api-reference/create-offramp-session.md), and the component runs every other step with Crossmint:

<Snippet file="offramp-embedded-where-it-runs.mdx" />

<Snippet file="offramp-embedded-session-backend.mdx" />

<Snippet file="offramp-embedded-session-fields.mdx" />

<Snippet file="offramp-embedded-https-backend.mdx" />

### 2. Render the offramp component

Create a screen that asks your backend for a session and renders `CrossmintEmbeddedOfframp`. `CrossmintEmbeddedOfframpPayer.wallet` turns the user's Crossmint wallet into the `payer` that signs and sends the deposit. The screen wraps it to keep **Close** disabled while the wallet signs, because the component has to stay on screen to pass the wallet's answer back to the offramp. With `fill: true`, the offramp fills the space its parent gives it and scrolls inside itself:

```dart lib/withdraw_screen.dart theme={null}
import 'dart:convert';

import 'package:crossmint_flutter/crossmint_flutter_ui.dart';
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;

// Replace with your backend URL.
const sessionUrl = 'https://YOUR_BACKEND_URL/api/offramp-session';

class WithdrawScreen extends StatefulWidget {
  const WithdrawScreen({
    super.key,
    required this.userId,
    required this.email,
    required this.wallet,
  });

  final String userId;
  final String email;
  final CrossmintRuntimeWalletBase wallet;

  @override
  State<WithdrawScreen> createState() => _WithdrawScreenState();
}

class _WithdrawScreenState extends State<WithdrawScreen> {
  CrossmintEmbeddedOfframpCredentials? _credentials;
  bool _isLoading = false;
  bool _isSigning = false;

  Future<void> _startWithdrawal() async {
    setState(() => _isLoading = true);
    try {
      final response = await http.post(
        Uri.parse(sessionUrl),
        headers: {'Content-Type': 'application/json'},
        body: jsonEncode({
          'userId': widget.userId,
          'receiptEmail': widget.email,
          'walletAddress': widget.wallet.address,
          'chain': widget.wallet.chain,
        }),
      );
      if (response.statusCode != 200) {
        throw Exception('Create Offramp Session failed (${response.statusCode}): ${response.body}');
      }
      final session = jsonDecode(response.body) as Map<String, dynamic>;
      if (!mounted) {
        return;
      }
      setState(() {
        _credentials = CrossmintEmbeddedOfframpCredentials(
          sessionId: session['sessionId'] as String,
          clientSecret: session['clientSecret'] as String,
        );
      });
    } catch (error) {
      debugPrint('Failed to create the offramp session: $error');
    } finally {
      if (mounted) {
        setState(() => _isLoading = false);
      }
    }
  }

  void _close() => setState(() => _credentials = null);

  // Keeps Close disabled while the wallet signs, so the reply reaches the offramp.
  CrossmintEmbeddedOfframpPayer _payer() {
    final walletPayer = CrossmintEmbeddedOfframpPayer.wallet(widget.wallet);
    return CrossmintEmbeddedOfframpPayer(
      signAndSendTransaction: (transaction) async {
        setState(() => _isSigning = true);
        try {
          return await walletPayer.signAndSendTransaction(transaction);
        } finally {
          if (mounted) {
            setState(() => _isSigning = false);
          }
        }
      },
    );
  }

  @override
  Widget build(BuildContext context) {
    final credentials = _credentials;
    if (credentials == null) {
      return Center(
        child: FilledButton(
          onPressed: _isLoading ? null : _startWithdrawal,
          child: Text(_isLoading ? 'Starting...' : 'Withdraw to bank'),
        ),
      );
    }
    return Column(
      children: [
        Align(
          alignment: Alignment.centerRight,
          child: TextButton(onPressed: _isSigning ? null : _close, child: const Text('Close')),
        ),
        Expanded(
          child: CrossmintEmbeddedOfframp(
            apiKey: const String.fromEnvironment('CROSSMINT_API_KEY'),
            credentials: credentials,
            payer: _payer(),
            fill: true,
            onStatusChange: (status, orderId) =>
                debugPrint('Offramp status: ${status.wireValue} $orderId'),
            onComplete: (orderId, txId) => debugPrint('Withdrawal sent: $orderId $txId'),
            onCancel: _close,
            onError: (error) => debugPrint(
              'Offramp error: ${error.reason.wireValue} ${error.retriable} ${error.message}',
            ),
          ),
        ),
      ],
    );
  }
}
```

Render `WithdrawScreen` with the user ID from your JWT, the user's email, and the runtime wallet you loaded in the wallets quickstart, for example `walletController.createEvmWallet()` after you set its signer with `useSigner`.

`CrossmintEmbeddedOfframpPayer.wallet` refuses a deposit prepared for another wallet or chain without sending anything, so render the component only while this wallet is the session's payer. Without `fill`, the component takes the height of the page, at least 650px plus padding, and grows when a screen needs more. See [Sizing](https://docs.crossmint.com/offramp/guides/ui-customization.md#sizing).

### 3. Handle the events

<Snippet file="offramp-embedded-handle-events.mdx" />

### 4. Test on staging

<Snippet file="offramp-embedded-test-on-staging.mdx" />

## Use an External Wallet

To withdraw from a wallet that Crossmint did not create, link it to the user with [Link External Wallet to User](https://docs.crossmint.com/api-reference/users/link-wallet.md) before you create the session, and pass your own `CrossmintEmbeddedOfframpPayer`. The component calls its `signAndSendTransaction` with the deposit to send:

* **`serializedTransaction`**: a serialized transaction on EVM chains, or a base58 legacy transaction with `feePayer` and `recentBlockhash` set on Solana.
* **`chain`** and **`payerAddress`**: the chain and wallet the deposit was prepared for. Do not send from a wallet that does not match: check it before you render the component. See [Refuse a mismatched wallet](https://docs.crossmint.com/offramp/guides/handle-events-and-errors.md#refuse-a-mismatched-wallet).

Sign and broadcast the transaction, then return its hash, or the signature on Solana. Throw `CrossmintOfframpSignatureRejectedException` only when the user declines and nothing was broadcast, so the component can offer the withdrawal again with a new rate:

```dart lib/external_wallet_payer.dart theme={null}
import 'package:crossmint_flutter/crossmint_flutter_ui.dart';

CrossmintEmbeddedOfframpPayer externalWalletPayer({
  // Your wallet code: sign and broadcast the transaction, and return its hash.
  required Future<String> Function(CrossmintOfframpTransaction transaction) sendWithYourWallet,
  // Your wallet code: true when the user declined the request in their wallet.
  required bool Function(Object error) isUserRejection,
}) {
  return CrossmintEmbeddedOfframpPayer(
    signAndSendTransaction: (transaction) async {
      try {
        return await sendWithYourWallet(transaction);
      } catch (error) {
        if (isUserRejection(error)) {
          throw const CrossmintOfframpSignatureRejectedException(
            'The user declined the transaction',
          );
        }
        rethrow;
      }
    },
  );
}
```

If an order needs proof that the user owns the wallet, pass `signMessage` to the payer. The component calls it with a Crossmint sign-in challenge for `payerAddress`. Return the EIP-191 `personal_sign` signature as a 0x-prefixed hex string on EVM chains, or the base64 encoding of the 64-byte ed25519 signature over the UTF-8 message on Solana. Without `signMessage`, the component stops with the `wallet-ownership-required` error. Link the wallet again with an ownership `proof`, then create a new session. For Solana deposits, see [Offramp Orders on Solana](https://docs.crossmint.com/offramp/guides/sign-deposit-solana.md).

## Troubleshooting

<Snippet file="offramp-embedded-troubleshooting.mdx" />

## Launching in Production

<Snippet file="offramp-embedded-launch.mdx" />

## Learn More

> [card] [Handle Offramp Events and Errors](https://docs.crossmint.com/offramp/guides/handle-events-and-errors.md)
>
> What each status and error reason means

> [card] [Flutter Wallets Quickstart](https://docs.crossmint.com/wallets/quickstarts/flutter.md)
>
> Load the user's wallet and its signer
