image

06 Dec 2025

9K

35K

Integrating Google Analytics into Flutter Applications

In the evolving landscape of mobile application development, understanding user behavior is paramount for creating successful and engaging products. Flutter, Google's UI toolkit for building natively compiled applications for mobile, web, and desktop from a single codebase, offers immense potential. To truly harness this potential, developers need robust analytics solutions. Google Analytics, specifically its integration with Firebase (GA4), provides a powerful platform for tracking, analyzing, and reporting user interactions within Flutter applications.

Why Integrate Google Analytics with Flutter?

Integrating Google Analytics into your Flutter application provides a wealth of benefits:

  • Data-Driven Decisions: Gain insights into how users interact with your app, identify popular features, and pinpoint areas for improvement.
  • User Behavior Analysis: Understand user journeys, retention rates, and conversion funnels across different platforms (iOS and Android) from a unified view.
  • Performance Monitoring: Track the performance of specific features or user flows and identify bottlenecks.
  • Personalization: Segment users based on their behavior and create tailored experiences.
  • Cross-Platform Consistency: Leverage a single analytics solution for both iOS and Android, ensuring consistent data collection and reporting.

Prerequisites

Before you begin, ensure you have the following:

  1. A Google Account.
  2. A Firebase Project with Google Analytics enabled. If you're creating a new Firebase project, ensure you enable Google Analytics during the setup process. For an existing project, you can link Google Analytics from the Project Settings.
  3. A Flutter project set up and ready for integration.

Step 1: Set Up Firebase Project and Link to Google Analytics (GA4)

Navigate to the Firebase Console. Create a new project or select an existing one. If creating a new project, follow the prompts and ensure you enable Google Analytics for this project. This step automatically links your Firebase project to a Google Analytics 4 (GA4) property.

For existing projects, go to Project settings (the gear icon) > Integrations > Google Analytics. Ensure it's enabled and linked.

Step 2: Add Firebase to Your Flutter Project

First, add the necessary Firebase dependencies to your Flutter project's pubspec.yaml file. You will primarily need firebase_core for Firebase initialization and firebase_analytics for analytics functionalities.


dependencies:
  flutter:
    sdk: flutter
  firebase_core: ^2.24.2 # Use the latest version
  firebase_analytics: ^10.7.2 # Use the latest version

Run flutter pub get to fetch these packages.

Next, configure your Flutter project to connect with your Firebase project. The recommended way is to use the FlutterFire CLI:


flutter pub global activate flutterfire_cli
flutterfire configure

Follow the on-screen prompts to select your Firebase project and the platforms you want to configure (Android, iOS, Web). This command generates the necessary configuration files (e.g., firebase_options.dart) for your Flutter app.

Step 3: Initialize Firebase and Google Analytics in Your Flutter App

Before using any Firebase service, you must initialize firebase_core. It's best practice to do this at the very beginning of your application, typically in your main() function.


import 'package:firebase_core/firebase_core.dart';
import 'package:firebase_analytics/firebase_analytics.dart';
import 'package:flutter/material.dart';
import 'firebase_options.dart'; // Generated by flutterfire configure

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

class MyApp extends StatelessWidget {
  const MyApp({super.key});

  static FirebaseAnalytics analytics = FirebaseAnalytics.instance;
  static FirebaseAnalyticsObserver observer = FirebaseAnalyticsObserver(analytics: analytics);

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Firebase Analytics',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      navigatorObservers: <NavigatorObserver>[observer],
      home: const MyHomePage(),
    );
  }
}

class MyHomePage extends StatefulWidget {
  const MyHomePage({super.key});

  @override
  State<MyHomePage> createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('Analytics Demo'),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            ElevatedButton(
              onPressed: () {
                // Log a custom event
                MyApp.analytics.logEvent(name: 'button_pressed', parameters: {'button_name': 'My Button'});
              },
              child: const Text('Log Custom Event'),
            ),
            ElevatedButton(
              onPressed: () {
                // Set user property
                MyApp.analytics.setUserProperty(name: 'user_type', value: 'premium');
              },
              child: const Text('Set User Property'),
            ),
          ],
        ),
      ),
    );
  }
}

In the MyApp widget, we initialize FirebaseAnalytics.instance and create a FirebaseAnalyticsObserver. By adding this observer to MaterialApp's navigatorObservers, Flutter automatically logs screen views as users navigate between routes.

Step 4: Logging Events

Google Analytics for Firebase (GA4) is event-centric. Everything you track is an event. The firebase_analytics package provides methods for logging predefined events and custom events.

Logging Predefined Events

Firebase Analytics offers a list of recommended events for various app types (e.g., e-commerce, gaming). Using these standard events allows GA4 to provide richer reporting.


// Example: Logging a login event
MyApp.analytics.logLogin(loginMethod: 'email_and_password');

// Example: Logging a purchase event
MyApp.analytics.logPurchase(
  currency: 'USD',
  value: 9.99,
  transactionId: 'TRX12345',
  items: [
    Item(
      itemId: 'SKU789',
      itemName: 'Premium Subscription',
      price: 9.99,
      quantity: 1,
    ),
  ],
);

// Example: Logging a search event
MyApp.analytics.logSearch(searchTerm: 'flutter widgets');

Logging Custom Events

For scenarios not covered by predefined events, you can log custom events with custom parameters.


// Example: Logging a custom event with parameters
MyApp.analytics.logEvent(
  name: 'level_up',
  parameters: <String, dynamic>{
    'level': 10,
    'character_name': 'HeroFlutter',
    'game_mode': 'adventure',
  },
);

// Example: Logging a button press with a dynamic value
void _onButtonPressed(String buttonName) {
  MyApp.analytics.logEvent(
    name: 'button_click',
    parameters: <String, dynamic>{
      'button_id': buttonName.toLowerCase().replaceAll(' ', '_'),
      'screen_name': ModalRoute.of(context)?.settings.name ?? 'unknown_screen',
    },
  );
}

Step 5: Setting User Properties

User properties describe segments of your user base, such as language preference or geographic location. You can define up to 25 unique user properties in your GA4 property.


// Example: Setting a user property for premium users
MyApp.analytics.setUserProperty(name: 'user_tier', value: 'premium');

// Example: Setting a user property for app version
MyApp.analytics.setUserProperty(name: 'app_version', value: '1.2.0');

// Example: Setting a user ID (for cross-device user identification)
MyApp.analytics.setUserId(id: 'user_12345');

Remember that user properties apply to all subsequent events from that user. They are not sent with historical data.

Debugging and Testing Your Analytics Implementation

To verify that your analytics events are being sent correctly, use Firebase's DebugView. This tool provides a real-time stream of events from your development devices.

Enabling Debug Mode:

  • For Android: Run your app with debug enabled. In your terminal, execute:
    
    adb shell setprop debug.firebase.analytics.app [YOUR_APP_PACKAGE_NAME]
            

    Replace [YOUR_APP_PACKAGE_NAME] with your app's package name (e.g., com.example.my_app). You can find this in your android/app/build.gradle file.

  • For iOS: In Xcode, select Product > Scheme > Edit Scheme. Select Run from the left menu. Under the Arguments tab, add -FIRDebugEnabled to "Arguments Passed On Launch".

After enabling debug mode, run your Flutter app and navigate to the Firebase Console, then go to Analytics > DebugView. You should see your events streaming in real-time.

Conclusion

Integrating Google Analytics into your Flutter application is a crucial step towards building a truly data-driven product. By leveraging Firebase Analytics (GA4), you gain a powerful toolset to understand user behavior, optimize features, and make informed decisions that drive growth and enhance user experience. Start collecting data today to unlock the full potential of your Flutter applications.

Join our newsletter!

Enter your email to receive our latest newsletter.

Don't worry, we don't spam

Categories

Related Articles

Dec 06, 2025

Integrating Google Analytics into Flutter Applications

Integrating Google Analytics into Flutter Applications In the evolving landscape of mobile application development, understanding user behavior is paramount fo

Dec 05, 2025

Flutter & JSON Parsing with Model Classes

Flutter & JSON Parsing with Model Classes Introduction In modern mobile application development, consuming data from web services is a fundamental requirement.

Dec 05, 2025

Creating Scrollable Lists in Flutter

Creating Scrollable Lists in Flutter Scrollable lists are a fundamental component of almost any modern mobile application, allowing users to