Why Choose stellar_flutter_sdk?

The stellar_flutter_sdk Flutter package gives Flutter developers a ready‑made client for Stellar's Horizon API and Soroban RPC. If your app needs to read account balances, submit payments, or interact with Soroban contracts, the SDK saves you from writing low‑level HTTP code and cryptographic helpers.

Tip: Keep all SDK calls behind a dedicated service layer. This isolates third‑party code and makes future upgrades easier.

When to Use This Package

  • Building a wallet, payment gateway, or any finance‑related feature on Stellar.
  • Fetching on‑chain data (balances, transaction history, ledger info) without reinventing networking code.
  • Creating, signing, and submitting transactions from a Flutter mobile or desktop client.
  • Interacting with Soroban smart contracts via the RPC endpoint.

Installation

Run the following command in your project root:

Code
flutter pub add stellar_flutter_sdk

After the package resolves, import it where you need it:

Code
import 'package:stellar_flutter_sdk/stellar_flutter_sdk.dart';

Basic Setup – A Service Example

Encapsulating SDK usage in a service class follows clean architecture principles. Below is a minimal StellarService that demonstrates account lookup and transaction submission.

Code
class StellarService {
  final Server _horizon;

  StellarService({String horizonUrl = 'https://horizon.stellar.org'})
      : _horizon = Server(horizonUrl);

  /// Fetches the account details for the given public key.
  Future<AccountResponse> getAccount(String accountId) async {
    try {
      return await _horizon.accounts.account(accountId);
    } catch (e) {
      // Propagate or transform the error as needed.
      rethrow;
    }
  }

  /// Sends a payment from [sourceSecret] to [destination] of [amount] XLM.
  Future<SubmitTransactionResponse> sendPayment({
    required String sourceSecret,
    required String destination,
    required String amount,
  }) async {
    // 1️⃣ Load the source keypair and account data.
    final sourceKeyPair = KeyPair.fromSecretSeed(sourceSecret);
    final sourceAccount = await _horizon.accounts.account(sourceKeyPair.accountId);

    // 2️⃣ Build the transaction.
    final transaction = TransactionBuilder(sourceAccount)
        .addOperation(PaymentOperation(
          destination,
          AssetTypeNative(),
          amount,
        ))
        .addMemo(Memo.text('FlutterFever demo'))
        .setTimeout(180)
        .build();

    // 3️⃣ Sign the transaction.
    transaction.sign(sourceKeyPair, Network.PUBLIC);

    // 4️⃣ Submit to Horizon.
    return await _horizon.submitTransaction(transaction);
  }
}

Inject StellarService into your UI layer (e.g., via Provider, Riverpod, or GetIt) and keep UI widgets free of direct SDK calls.

Fetching Account Details – A Quick Example

Code
Future<void> demoFetch() async {
  final service = StellarService();
  const publicKey = 'GXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX';

  try {
    final account = await service.getAccount(publicKey);
    print('Balances for ${account.accountId}:');
    for (final bal in account.balances) {
      final asset = bal.asset is AssetTypeNative ? 'XLM' : bal.asset.code;
      print('- $asset: ${bal.balance}');
    }
  } catch (e) {
    print('Error fetching account: $e');
  }
}

Submitting a Simple Payment Transaction

Code
Future<void> demoPayment() async {
  final service = StellarService();
  const sourceSecret = 'SXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX';
  const destination = 'GYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYY';
  const amount = '10'; // 10 XLM

  try {
    final response = await service.sendPayment(
      sourceSecret: sourceSecret,
      destination: destination,
      amount: amount,
    );
    if (response.success) {
      print('Payment succeeded! Tx hash: ${response.hash}');
    } else {
      print('Payment failed: ${response.resultXdr}');
    }
  } catch (e) {
    print('Transaction error: $e');
  }
}

Important Setup Notes

  • Use the correct Network constant (Network.PUBLIC or Network.TESTNET) that matches the Horizon URL.
  • Never hard‑code secret seeds in production code. Store them securely (e.g., encrypted storage).
  • For Soroban contract calls, replace TransactionBuilder operations with InvokeHostFunctionOperation as described in the SDK README.

Common Mistakes & How to Avoid Them

  • Mismatched network constants: Submitting a transaction to the public network while using the testnet Horizon endpoint will cause a Bad Request error. Always align Network with the Horizon URL.
  • Missing timeout: Horizon rejects transactions without a timeout. The SDK’s TransactionBuilder requires .setTimeout() – set a reasonable value (e.g., 180 seconds).
  • Improper error handling: The SDK throws StellarSdkException for network or protocol errors. Catch the specific exception to surface user‑friendly messages.
  • Exposing secret keys: Accidentally committing a secret seed to version control is a security risk. Use environment variables or secure key‑vault solutions.

Testing the Integration

During development, point the SDK at the testnet Horizon endpoint (https://horizon-testnet.stellar.org) and use the Friendbot service to fund accounts. This isolates your production keys from accidental test transactions.

Code
final testService = StellarService(horizonUrl: 'https://horizon-testnet.stellar.org');

Conclusion

The stellar_flutter_sdk Flutter package provides a robust, production‑ready way to interact with Stellar from Flutter. By installing the package, wrapping it in a service layer, and following the best‑practice tips above, you can add wallet‑style features, payment flows, or Soroban contract interactions with confidence.

Remember: always verify the latest API surface on pub.dev before shipping to production.

Frequently Asked Questions

Do I need to use a specific Flutter version for stellar_flutter_sdk?

The package declares its own SDK constraints on pub.dev. Check the <a href="https://pub.dev/packages/stellar_flutter_sdk" target="_blank">pub.dev page</a> for the minimum Dart/Flutter version and ensure your project meets that requirement.

Can I use stellar_flutter_sdk on both Android and iOS?

Yes. The SDK is pure Dart and does not rely on platform‑specific code, so it works on Android, iOS, web, and desktop as long as the underlying network connectivity is available.

How do I switch between the public network and testnet?

Code
Instantiate <code>Server</code> with the appropriate Horizon URL and use the matching <code>Network</code> constant:
<pre><code class="language-dart">final server = Server('https://horizon-testnet.stellar.org');
final network = Network.TESTNET;
</code></pre>
For production, use <code>https://horizon.stellar.org</code> and <code>Network.PUBLIC</code>.

Is there built‑in support for Soroban contracts?

The SDK includes RPC helpers for Soroban. Refer to the official documentation for <code>InvokeHostFunctionOperation</code> and related classes. The API may evolve, so always verify the latest usage examples on the package docs.

What should I do if a transaction fails with a <code>Bad Request</code> error?

Common causes are mismatched network constants, missing timeout, or an invalid sequence number. Retrieve the latest account state before building the transaction, set a timeout, and ensure you use the correct <code>Network</code> constant.