Dart / Flutter SDK
The kitbase_analytics package lets you track events from any Dart or Flutter application. It provides a simple, typed API with full error handling support.
Dart and Flutter
This SDK works with both standalone Dart applications and Flutter apps on all platforms (iOS, Android, Web, macOS, Windows, Linux).
Installation
Add kitbase_analytics to your pubspec.yaml:
dependencies:
kitbase_analytics: ^0.1.0Then run:
dart pub getflutter pub getQuick Start
import 'package:kitbase_analytics/events.dart';
final kitbase = KitbaseAnalytics();
// Track an event
final response = await kitbase.track(
channel: 'payments',
event: 'New Subscription',
userId: 'user-123',
icon: '💰',
notify: true,
description: 'User subscribed to premium plan',
tags: {
'plan': 'premium',
'cycle': 'monthly',
'amount': 9.99,
},
);
print('Event tracked: ${response.id}');Parameters
| Parameter | Type | Required | Description |
|---|---|---|---|
channel | String | Yes | Category for the event (e.g., "payments", "users") |
event | String | Yes | Name of the event (e.g., "New Subscription") |
userId | String? | No | Identifier for the user |
icon | String? | No | Emoji or icon name |
notify | bool? | No | Send real-time notification |
description | String? | No | Additional context about the event |
tags | Map<String, dynamic>? | No | Key-value metadata |
Channel Naming
Use lowercase, plural nouns for channel names. This keeps your events organized and easy to filter in the dashboard.
Response
The track() method returns a Future<TrackResponse> with the following fields:
class TrackResponse {
final String id; // Unique event ID (e.g., "evt_abc123")
final String event; // Event name
final String timestamp; // ISO 8601 timestamp
}Example usage:
final response = await kitbase.track(
channel: 'users',
event: 'User Signed Up',
);
print('Event ID: ${response.id}');
print('Tracked at: ${response.timestamp}');Tags
Tags are key-value pairs that add context to your events. They support three value types:
| Type | Dart Type | Example |
|---|---|---|
| String | String | 'premium' |
| Number | num / int / double | 99.99 |
| Boolean | bool | true |
await kitbase.track(
channel: 'payments',
event: 'Subscription Created',
tags: {
'plan': 'premium', // String
'amount': 99.99, // double
'is_first_purchase': true, // bool
'referral_code': 'SAVE20', // String
},
);Tag Naming
Use lowercase snake_case for tag keys:
user_type,plan_name,error_code- Not:
UserType,planName,ERROR-CODE
Error Handling
The SDK provides typed exceptions so you can handle specific error conditions precisely using Dart's on / catch syntax.
Exception Types
| Exception | Description |
|---|---|
KitbaseValidationException | Missing or invalid required fields (has field property) |
KitbaseAuthenticationException | Invalid or missing API key |
KitbaseApiException | API returned an error (has statusCode, response) |
KitbaseConnectionException | Network connectivity error |
KitbaseTimeoutException | Request exceeded timeout |
Basic Error Handling
import 'package:kitbase_analytics/events.dart';
try {
await kitbase.track(
channel: 'payments',
event: 'New Subscription',
);
} on KitbaseAuthenticationException {
// Invalid API key - check your token
print('Authentication failed');
} on KitbaseValidationException catch (e) {
// Missing required fields
print('Validation error: ${e.field}');
} on KitbaseTimeoutException {
// Request timed out - retry later
print('Request timed out');
} on KitbaseApiException catch (e) {
// API returned an error
print('API error: ${e.statusCode}');
print(e.response);
} on KitbaseConnectionException {
// Network error - check connectivity
print('No network connection');
}Retry with Exponential Backoff
For transient errors like timeouts and server errors, implement exponential backoff:
import 'dart:math';
import 'package:kitbase_analytics/events.dart';
Future<TrackResponse> trackWithRetry(
KitbaseAnalytics kitbase, {
required String channel,
required String event,
Map<String, dynamic>? tags,
int retries = 3,
}) async {
for (var attempt = 1; attempt <= retries; attempt++) {
try {
return await kitbase.track(
channel: channel,
event: event,
tags: tags,
);
} on KitbaseAuthenticationException {
rethrow; // Don't retry auth errors
} on KitbaseValidationException {
rethrow; // Don't retry validation errors
} on KitbaseTimeoutException {
if (attempt < retries) {
await Future.delayed(Duration(seconds: pow(2, attempt).toInt()));
continue;
}
rethrow;
} on KitbaseConnectionException {
if (attempt < retries) {
await Future.delayed(Duration(seconds: pow(2, attempt).toInt()));
continue;
}
rethrow;
} on KitbaseApiException catch (e) {
if (e.statusCode >= 500 && attempt < retries) {
await Future.delayed(Duration(seconds: pow(2, attempt).toInt()));
continue;
}
rethrow;
}
}
throw Exception('Max retries exceeded');
}Graceful Degradation
Don't let tracking failures break your application. Wrap calls in a safe helper:
Future<void> safeTrack({
required String channel,
required String event,
String? userId,
Map<String, dynamic>? tags,
}) async {
try {
await kitbase.track(
channel: channel,
event: event,
userId: userId,
tags: tags,
);
} catch (e) {
// Log but don't throw - tracking is non-critical
print('Event tracking failed: $e');
}
}Use Cases
Track User Signups (Flutter)
await kitbase.track(
channel: 'users',
event: 'User Signed Up',
userId: user.email,
icon: '👤',
notify: true,
description: 'New user from ${user.referralSource}',
tags: {
'source': user.referralSource,
'plan': 'free',
'platform': Theme.of(context).platform.name,
},
);Track Payments
await kitbase.track(
channel: 'payments',
event: 'Subscription Created',
userId: user.id,
icon: '💰',
notify: true,
tags: {
'plan': subscription.plan,
'amount': subscription.amount,
'currency': 'USD',
'interval': 'monthly',
},
);Track Errors
try {
await performCriticalOperation();
} catch (error, stackTrace) {
await kitbase.track(
channel: 'errors',
event: 'Critical Error',
icon: '🔴',
notify: true,
description: error.toString(),
tags: {
'error_type': error.runtimeType.toString(),
'stack_trace': stackTrace.toString().substring(0, 500),
},
);
}Track Feature Usage
await kitbase.track(
channel: 'features',
event: 'Export Generated',
userId: user.id,
icon: '📊',
tags: {
'format': 'pdf',
'pages': 15,
'duration_ms': stopwatch.elapsedMilliseconds,
},
);Next Steps
- Custom Events - Learn more about channels, tags, and notifications
- User Identity - Associate events with users
- Error Handling - Full error handling reference for all SDKs
- Privacy - Privacy and data collection details