Integrate Firebase Google Analytics in Flutter Application

Install firebase cli

Install firebase cli – https://firebase.google.com/docs/cli#setup_update_cli

Once you have installed, please verify using following command in command prompt

firebase -V

Login to firebase

firebase login
firebase logout
dart pub global activate flutterfire_cli

flutter pub add firebase_core

flutterfire configure

create or select project
select platforms

Goto https://console.firebase.google.com/u/0

Analytics-> Dashboard-> Enable Google Analytics

Package: https://pub.dev/packages/firebase_analytics
flutter pub add firebase_analytics

Firebase setup completed

CODING

lib/firebase_analytics_service.dart

import 'package:firebase_analytics/firebase_analytics.dart';
import 'package:flutter/foundation.dart';

class FirebaseAnalyticsService {
  final FirebaseAnalytics _analytics = FirebaseAnalytics.instance;
  FirebaseAnalyticsObserver getFirebaseAnalyticsObserver(){
    debugPrint("getFirebaseAnalyticsObserver: ");
    return FirebaseAnalyticsObserver(analytics: _analytics);
  }
      

  Future<void> logFirebaseEvent(
      String eventName, Map<String, Object>? parameters) async {
    await _analytics.logEvent(name: eventName, parameters: parameters);
  }

  Future<void> logFirebaseAppOpen() async{
    await _analytics.logAppOpen();
  }
}

/**
// Example usage:
FirebaseAnalyticsService().logFirebaseEvent(
            'button_click', {'button_name': 'welcomeFormSubmitAction'});
 */

main.dart

void main() async {
  WidgetsFlutterBinding.ensureInitialized();
  await Firebase.initializeApp(options: DefaultFirebaseOptions.currentPlatform);
}

GetMaterialApp

Widget build(BuildContext context) {
 FirebaseAnalyticsService().logFirebaseAppOpen();
 return GetMaterialApp(
      ....
      initialRoute: '/',
      navigatorObservers: [
        FirebaseAnalyticsService().getFirebaseAnalyticsObserver(),
      ],
      ....
    );
}

Leave a Reply

Your email address will not be published. Required fields are marked *

Exit mobile version