Skip to main content

Complete Integration Example

The example below ties everything from the previous sections into a single, realistic integration. It shows what a typical e-commerce application looks like once the SDK is wired in end-to-end: initialization with full configuration, push token registration, an add-to-cart event with item-level data, and a purchase event followed by an immediate flush so the critical revenue data leaves the device right away. You can use this snippet as a reference when integrating the SDK in your own application — replace the screen and handler stubs with your real code, and the rest stays valid.

import 'package:flutter/material.dart';
import 'package:b2metric_sdk/b2metric_sdk.dart';

void main() async {
WidgetsFlutterBinding.ensureInitialized();

// 1. Initialize the SDK
await B2Metric.instance.init(
const B2MetricConfig(
apiKey: 'YOUR_API_KEY',
batchSize: 20,
flushIntervalSeconds: 30,
sessionTimeoutMinutes: 30,
logLevel: LogLevel.debug,
),
);

// 2. Register the push token once obtained
// final token = await FirebaseMessaging.instance.getToken();
// B2Metric.instance.registerPushToken(token!, PushProvider.fcm);

runApp(const MyApp());
}

class ProductScreen extends StatelessWidget {
void _onAddToCart() {
B2Metric.instance.logEvent(
'add_to_cart',
properties: {
'total': 5700,
'currency': 'USD',
},
itemProperties: [
{'id': 'SKU-001', 'name': 'Running Shoes', 'price': 2850, 'quantity': 1},
{'id': 'SKU-002', 'name': 'Athletic Socks', 'price': 150, 'quantity': 3},
],
);
}

Future<void> _onPurchaseComplete(String orderId) async {
B2Metric.instance.logEvent(
'purchase_completed',
properties: {
'order_id': orderId,
'total': 5700,
'currency': 'USD',
'payment': 'credit_card',
},
);

// Critical event — flush immediately
await B2Metric.instance.flush();
}

@override
Widget build(BuildContext context) {
return Container();
}
}