Getting Started with Flutter SDK
This guide will help you integrate the Reachu Flutter SDK into your app and manage shopping carts, payments, and ecommerce functionality in just a few minutes.
Prerequisites
Before you start, make sure you have:
- Flutter SDK installed (version 3.0 or higher)
- Dart SDK (version 2.17 or higher)
- Reachu API Key - Get one here
- Basic knowledge of Flutter and Dart
Installation
1. Add Dependencies
Add the Reachu Flutter SDK to your pubspec.yaml
file:
dependencies:
flutter:
sdk: flutter
# Reachu SDK
reachu_flutter_sdk: ^1.0.0
# Optional: Environment variables support
flutter_dotenv: ^5.1.0
# Optional: UUID generation
uuid: ^3.0.7
flutter:
assets:
- .env # If using environment variables
2. Install Packages
Run the following command to install the packages:
dart pub get
Setup & Configuration
1. Environment Setup (Recommended)
Create a .env
file in your project root to keep your API keys secure:
GRAPHQL_ENDPOINT=https://graph-ql-dev.reachu.io
API_KEY=Bearer YOUR_TOKEN_HERE
2. Create SDK Service
Create a singleton service to manage the SDK instance:
import 'package:reachu_flutter_sdk/reachu_flutter_sdk.dart';
class SdkService {
static final SdkService _instance = SdkService._internal();
late final SdkClient sdk;
factory SdkService() => _instance;
SdkService._internal();
void init({required String baseUrl, required String apiKey}) {
sdk = SdkClient(baseUrl: baseUrl, apiKey: apiKey);
}
}
3. Initialize in Main
import 'package:flutter/material.dart';
import 'package:flutter_dotenv/flutter_dotenv.dart';
import 'package:uuid/uuid.dart';
import 'services/sdk_service.dart';
void main() async {
WidgetsFlutterBinding.ensureInitialized();
// Load environment variables
await dotenv.load(fileName: ".env");
// Initialize SDK
SdkService().init(
baseUrl: dotenv.env['GRAPHQL_ENDPOINT']!,
apiKey: dotenv.env['API_KEY']!,
);
// Create initial cart
final uuid = const Uuid().v4();
final createdCart = await SdkService().sdk.cart.create(
customer_session_id: uuid,
currency: 'USD',
);
runApp(MyApp(initialCartId: createdCart.cartId));
}
class MyApp extends StatelessWidget {
final String initialCartId;
const MyApp({super.key, required this.initialCartId});
Widget build(BuildContext context) {
return MaterialApp(
title: 'Reachu Flutter Demo',
theme: ThemeData(primarySwatch: Colors.blue),
home: ShoppingScreen(cartId: initialCartId),
);
}
}
Your First SDK Operations
Now let's implement basic shopping cart functionality using the SDK:
1. Create Shopping Screen
import 'package:flutter/material.dart';
import '../services/sdk_service.dart';
class ShoppingScreen extends StatefulWidget {
final String cartId;
const ShoppingScreen({super.key, required this.cartId});
State<ShoppingScreen> createState() => _ShoppingScreenState();
}
class _ShoppingScreenState extends State<ShoppingScreen> {
Map<String, dynamic>? cart;
List<Map<String, dynamic>> products = [];
bool isLoading = true;
void initState() {
super.initState();
_loadData();
}
Future<void> _loadData() async {
try {
// Get cart details
final cartData = await SdkService().sdk.cart.getById(cart_id: widget.cartId);
// Get available products
final productData = await SdkService().sdk.channel.product.get(
currency: 'USD',
useCache: true,
);
setState(() {
cart = cartData.toJson();
products = productData.map((p) => p.toJson()).toList();
isLoading = false;
});
} catch (e) {
setState(() {
isLoading = false;
});
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(content: Text('Error loading data: $e')),
);
}
}
Future<void> _addToCart(int productId, int variantId) async {
try {
final updatedCart = await SdkService().sdk.cart.addItem(
cart_id: widget.cartId,
line_items: {
'product_id': productId,
'quantity': 1,
'variant_id': variantId,
},
);
setState(() {
cart = updatedCart.toJson();
});
ScaffoldMessenger.of(context).showSnackBar(
const SnackBar(content: Text('Item added to cart!')),
);
} catch (e) {
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(content: Text('Error adding to cart: $e')),
);
}
}
Widget build(BuildContext context) {
if (isLoading) {
return const Scaffold(
body: Center(child: CircularProgressIndicator()),
);
}
return Scaffold(
appBar: AppBar(
title: const Text('Reachu Shopping'),
actions: [
IconButton(
icon: const Icon(Icons.shopping_cart),
onPressed: () => _showCart(),
),
],
),
body: ListView.builder(
itemCount: products.length,
itemBuilder: (context, index) {
final product = products[index];
return ProductTile(
product: product,
onAddToCart: () => _addToCart(
product['id'],
product['variants']?[0]?['id'] ?? 0,
),
);
},
),
);
}
void _showCart() {
showDialog(
context: context,
builder: (context) => AlertDialog(
title: const Text('Cart'),
content: Text('Cart ID: ${widget.cartId}\n'
'Items: ${cart?['line_items']?.length ?? 0}'),
actions: [
TextButton(
onPressed: () => Navigator.pop(context),
child: const Text('Close'),
),
],
),
);
}
}
class ProductTile extends StatelessWidget {
final Map<String, dynamic> product;
final VoidCallback onAddToCart;
const ProductTile({
super.key,
required this.product,
required this.onAddToCart,
});
Widget build(BuildContext context) {
return Card(
margin: const EdgeInsets.all(8.0),
child: ListTile(
leading: const Icon(Icons.shopping_bag),
title: Text(product['title'] ?? 'Unknown Product'),
subtitle: Text(product['description'] ?? ''),
trailing: ElevatedButton(
onPressed: onAddToCart,
child: const Text('Add'),
),
),
);
}
}
🧪 Test Your Setup
-
Run your app:
flutter run
-
Verify the connection: You should see:
- A cart created automatically on app start
- Products loaded from your channel
- Ability to add items to cart
-
Check for errors: Look at the debug console for any SDK or network errors
🚀 Next Steps
Congratulations! You now have a working Flutter app with Reachu SDK. Here's what to explore next:
- API Reference - Complete SDK method documentation
- Cart Management - Advanced cart operations
- Payment Integration - Stripe, Klarna, Vipps
- UI Components - Pre-built Flutter widgets
- Examples - Complete app examples
🚨 Common Issues
SDK Initialization Errors
- ✅ Check your API key is correct and includes "Bearer " prefix
- ✅ Verify you're using the right endpoint (dev vs production)
- ✅ Ensure internet connection is working
Build Errors
- ✅ Run
flutter clean && dart pub get
- ✅ Check Flutter and Dart versions compatibility
- ✅ Verify all dependencies are compatible
Cart/Product Errors
- ✅ Make sure your API key has proper permissions
- ✅ Check if products exist in your channel
- ✅ Verify currency codes are supported
Environment Variables Not Loading
- ✅ Ensure
.env
file is in project root - ✅ Check flutter assets includes
.env
inpubspec.yaml
- ✅ Verify environment variable names match exactly
Check out the example project or contact us at support@reachu.io