Skip to content

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:

yaml
dependencies:
  kitbase_analytics: ^0.1.0

Then run:

bash
dart pub get
bash
flutter pub get

Quick Start

dart
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

ParameterTypeRequiredDescription
channelStringYesCategory for the event (e.g., "payments", "users")
eventStringYesName of the event (e.g., "New Subscription")
userIdString?NoIdentifier for the user
iconString?NoEmoji or icon name
notifybool?NoSend real-time notification
descriptionString?NoAdditional context about the event
tagsMap<String, dynamic>?NoKey-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:

dart
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:

dart
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:

TypeDart TypeExample
StringString'premium'
Numbernum / int / double99.99
Booleanbooltrue
dart
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

ExceptionDescription
KitbaseValidationExceptionMissing or invalid required fields (has field property)
KitbaseAuthenticationExceptionInvalid or missing API key
KitbaseApiExceptionAPI returned an error (has statusCode, response)
KitbaseConnectionExceptionNetwork connectivity error
KitbaseTimeoutExceptionRequest exceeded timeout

Basic Error Handling

dart
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:

dart
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:

dart
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)

dart
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

dart
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

dart
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

dart
await kitbase.track(
  channel: 'features',
  event: 'Export Generated',
  userId: user.id,
  icon: '📊',
  tags: {
    'format': 'pdf',
    'pages': 15,
    'duration_ms': stopwatch.elapsedMilliseconds,
  },
);

Next Steps

Released under the MIT License.