89 lines
2.4 KiB
Dart
89 lines
2.4 KiB
Dart
import 'package:firebase_analytics/firebase_analytics.dart';
|
|
import 'package:flutter/foundation.dart';
|
|
import 'package:flutter/material.dart';
|
|
|
|
/// Firebase Analytics service for tracking user events across the app.
|
|
///
|
|
/// Usage:
|
|
/// ```dart
|
|
/// // Log add to cart event
|
|
/// AnalyticsService.logAddToCart(
|
|
/// productId: 'SKU123',
|
|
/// productName: 'Gạch men 60x60',
|
|
/// price: 150000,
|
|
/// quantity: 2,
|
|
/// );
|
|
/// ```
|
|
class AnalyticsService {
|
|
AnalyticsService._();
|
|
|
|
static final FirebaseAnalytics _analytics = FirebaseAnalytics.instance;
|
|
|
|
/// Get the analytics instance for NavigatorObserver
|
|
static FirebaseAnalytics get instance => _analytics;
|
|
|
|
/// Get the observer for automatic screen tracking in GoRouter
|
|
static FirebaseAnalyticsObserver get observer => FirebaseAnalyticsObserver(
|
|
analytics: _analytics,
|
|
nameExtractor: (settings) {
|
|
// GoRouter uses the path as the route name
|
|
final name = settings.name;
|
|
if (name != null && name.isNotEmpty && name != '/') {
|
|
return name;
|
|
}
|
|
return settings.name ?? '/';
|
|
},
|
|
routeFilter: (route) => route is PageRoute,
|
|
);
|
|
|
|
/// Log screen view manually
|
|
static Future<void> logScreenView({
|
|
required String screenName,
|
|
String? screenClass,
|
|
}) async {
|
|
try {
|
|
await _analytics.logScreenView(
|
|
screenName: screenName,
|
|
screenClass: screenClass,
|
|
);
|
|
debugPrint('📊 Analytics: screen_view - $screenName');
|
|
} catch (e) {
|
|
debugPrint('📊 Analytics error: $e');
|
|
}
|
|
}
|
|
|
|
/// Log add to cart event
|
|
///
|
|
/// [productId] - Product SKU or ID
|
|
/// [productName] - Product display name
|
|
/// [price] - Unit price in VND
|
|
/// [quantity] - Quantity added
|
|
/// [category] - Optional product category
|
|
static Future<void> logAddToCart({
|
|
required String productId,
|
|
required String productName,
|
|
required double price,
|
|
required int quantity,
|
|
String? brand,
|
|
}) async {
|
|
try {
|
|
await _analytics.logAddToCart(
|
|
currency: 'VND',
|
|
value: price * quantity,
|
|
items: [
|
|
AnalyticsEventItem(
|
|
itemId: productId,
|
|
itemName: productName,
|
|
price: price,
|
|
quantity: quantity,
|
|
itemBrand: brand,
|
|
),
|
|
],
|
|
);
|
|
debugPrint('📊 Analytics: add_to_cart - $productName x$quantity');
|
|
} catch (e) {
|
|
debugPrint('📊 Analytics error: $e');
|
|
}
|
|
}
|
|
}
|