You are currently viewing Flutter Firebase Analytics Example

Flutter Firebase Analytics Example

If you are creating an app and you have a fair amount of users, you may need to know the screens and sections of your app that are of most interest to your users. This allows you to optimize the app better for better user experience as well as more revenue.

This tutorial explores Flutter Firebase Analytics Examples.

Example 1: Flutter Firebase Analytics Example

Here is the project classes:

  1. main.dart
  2. single_item_tile.dart

Here is what is created in this example.


Step 1: Install Dependencies

You need two external dependencies: the firebase core as well as firebase analytics.

In your pubspec.yaml add the following then pub get:

  firebase_analytics: ^6.0.2
  firebase_core: ^0.5.0+1

Step 2: Create a single item tile

Create a file named single_item_named.dart. Then import packages:

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

Create a single item tile that extends the Stateful widget:

class SingleItemTile extends StatefulWidget {
  final String price;
  final String itemName;
  final double quantity;
  final FirebaseAnalytics analytics;
  SingleItemTile({
    this.itemName,
    this.price,
    this.quantity,
    this.analytics,
  });
  @override
  _SingleItemTileState createState() => _SingleItemTileState();
}

Now create a single item title class:

class _SingleItemTileState extends State<SingleItemTile> {
  /// [addedToCart] this variable is used to to justify that product is added in
  /// cart or not
  bool addedToCart;
  @override
  void initState() {
    addedToCart = false;
    super.initState();
  }
  @override
  Widget build(BuildContext context) {
    return Container(
      decoration: BoxDecoration(
        borderRadius: BorderRadius.circular(10),
        border: Border.all(
          color: Colors.green,
        ),
      ),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Image.asset(
            'asset/carrot.jpg',
            height: 200,
            width: 400,
          ),
          Container(
            color: Colors.green,
            height: .5,
            width: double.infinity,
          ),
          Padding(
            padding: const EdgeInsets.all(16.0) + EdgeInsets.only(left: 8),
            child: Row(
              mainAxisSize: MainAxisSize.max,
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              children: [
                Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    Text(
                      widget.price,
                      style: TextStyle(
                        color: Colors.red[600],
                        fontWeight: FontWeight.bold,
                        fontSize: 18,
                      ),
                    ),
                    Text(
                      widget.itemName,
                      style: TextStyle(
                        color: Colors.black,
                        fontSize: 16,
                      ),
                    ),
                    Text(
                      widget.quantity.toString() + ' kg',
                      style: TextStyle(
                        color: Colors.grey,
                        fontSize: 12,
                      ),
                    ),
                  ],
                ),
                InkWell(
                  onTap: () {
                    setState(() {
                      addedToCart = !addedToCart;
                    });
                    _sendCartEvent(widget.price, widget.itemName,
                        widget.quantity, addedToCart);
                  },
                  child: Container(
                    decoration: BoxDecoration(
                      borderRadius: BorderRadius.circular(10),
                      border: Border.all(
                        color: Colors.green,
                      ),
                    ),
                    child: Padding(
                      padding: const EdgeInsets.all(12.0),
                      child: Text(
                        addedToCart ? 'Remove from Cart' : 'Add to Cart +',
                        style: TextStyle(
                          color: Colors.red[600],
                          fontWeight: FontWeight.bold,
                          fontSize: 16,
                        ),
                      ),
                    ),
                  ),
                ),
              ],
            ),
          ),
        ],
      ),
    );
  }

Here is the full code:

single_item_tile.dart

import 'package:firebase_analytics/firebase_analytics.dart';
import 'package:flutter/material.dart';
class SingleItemTile extends StatefulWidget {
  final String price;
  final String itemName;
  final double quantity;
  final FirebaseAnalytics analytics;
  SingleItemTile({
    this.itemName,
    this.price,
    this.quantity,
    this.analytics,
  });
  @override
  _SingleItemTileState createState() => _SingleItemTileState();
}
class _SingleItemTileState extends State<SingleItemTile> {
  /// [addedToCart] this variable is used to to justify that product is added in
  /// cart or not
  bool addedToCart;
  @override
  void initState() {
    addedToCart = false;
    super.initState();
  }
  @override
  Widget build(BuildContext context) {
    return Container(
      decoration: BoxDecoration(
        borderRadius: BorderRadius.circular(10),
        border: Border.all(
          color: Colors.green,
        ),
      ),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Image.asset(
            'asset/carrot.jpg',
            height: 200,
            width: 400,
          ),
          Container(
            color: Colors.green,
            height: .5,
            width: double.infinity,
          ),
          Padding(
            padding: const EdgeInsets.all(16.0) + EdgeInsets.only(left: 8),
            child: Row(
              mainAxisSize: MainAxisSize.max,
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              children: [
                Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    Text(
                      widget.price,
                      style: TextStyle(
                        color: Colors.red[600],
                        fontWeight: FontWeight.bold,
                        fontSize: 18,
                      ),
                    ),
                    Text(
                      widget.itemName,
                      style: TextStyle(
                        color: Colors.black,
                        fontSize: 16,
                      ),
                    ),
                    Text(
                      widget.quantity.toString() + ' kg',
                      style: TextStyle(
                        color: Colors.grey,
                        fontSize: 12,
                      ),
                    ),
                  ],
                ),
                InkWell(
                  onTap: () {
                    setState(() {
                      addedToCart = !addedToCart;
                    });
                    _sendCartEvent(widget.price, widget.itemName,
                        widget.quantity, addedToCart);
                  },
                  child: Container(
                    decoration: BoxDecoration(
                      borderRadius: BorderRadius.circular(10),
                      border: Border.all(
                        color: Colors.green,
                      ),
                    ),
                    child: Padding(
                      padding: const EdgeInsets.all(12.0),
                      child: Text(
                        addedToCart ? 'Remove from Cart' : 'Add to Cart +',
                        style: TextStyle(
                          color: Colors.red[600],
                          fontWeight: FontWeight.bold,
                          fontSize: 16,
                        ),
                      ),
                    ),
                  ),
                ),
              ],
            ),
          ),
        ],
      ),
    );
  }
  /// to make custom event in Analytics you can create your own Map
  /// below in [name] field give your event name identifier
  /// and in [parameters] filed create your map
  Future<void> _sendCartEvent(
      String price, String itemName, double quantity, bool addedToCart) async {
    await widget.analytics.logEvent(
      name: 'item',
      parameters: <String, dynamic>{
        'price': price,
        'itemName': itemName,
        'quantity': quantity,
        'bool': addedToCart,
      },
    );
  }
}

Step 3: Create Main class

Create a file named main.dart. Add the following imports:

import 'package:analytics_integration/single_item_tile.dart';
import 'package:firebase_analytics/firebase_analytics.dart';
import 'package:firebase_analytics/observer.dart';
import 'package:firebase_core/firebase_core.dart';
import 'package:flutter/material.dart';

Create a FirebaseAnalyticsApp class that extends the StatelessWidget class:

class FlutterAnalyticsApp extends StatelessWidget {

In it instatiate the FirebaseAnalytics statically;

  static FirebaseAnalytics analytics = FirebaseAnalytics();

Create an observer taht sends events to Firebase Analytics when the currently active route changes:

  static FirebaseAnalyticsObserver observer =
      FirebaseAnalyticsObserver(analytics: analytics);

Now build the widget:

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Analytics',
      debugShowCheckedModeBanner: false,
      theme: ThemeData(
        primarySwatch: Colors.blue,
        visualDensity: VisualDensity.adaptivePlatformDensity,
      ),
      /// this is used to observe navigation changes in the app
      /// and sending data back to Firebase Analytics
      navigatorObservers: <NavigatorObserver>[observer],
      home: FlutterAnalyticsHome(
        title: 'Flutter Analytics',
        analytics: analytics,
        observer: observer,
      ),
    );
  }

Create the main method. In it initialize your firebase project, then run the FlutterAnalyticsApp:

void main() async {
  WidgetsFlutterBinding.ensureInitialized();
  /// initialize your firebase project
  await Firebase.initializeApp();
  runApp(FlutterAnalyticsApp());
}

Here is the full code:

main.dart

import 'package:analytics_integration/single_item_tile.dart';
import 'package:firebase_analytics/firebase_analytics.dart';
import 'package:firebase_analytics/observer.dart';
import 'package:firebase_core/firebase_core.dart';
import 'package:flutter/material.dart';
void main() async {
  WidgetsFlutterBinding.ensureInitialized();
  /// initialize your firebase project
  await Firebase.initializeApp();
  runApp(FlutterAnalyticsApp());
}
class FlutterAnalyticsApp extends StatelessWidget {
  /// create instance of FirebaseAnalytics as [analytics]
  static FirebaseAnalytics analytics = FirebaseAnalytics();
  /// create observer for FirebaseAnalytics as [observer]
  /// this observer sends events to Firebase Analytics when the
  /// currently active route changes.
  static FirebaseAnalyticsObserver observer =
      FirebaseAnalyticsObserver(analytics: analytics);
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Analytics',
      debugShowCheckedModeBanner: false,
      theme: ThemeData(
        primarySwatch: Colors.blue,
        visualDensity: VisualDensity.adaptivePlatformDensity,
      ),
      /// this is used to observe navigation changes in the app
      /// and sending data back to Firebase Analytics
      navigatorObservers: <NavigatorObserver>[observer],
      home: FlutterAnalyticsHome(
        title: 'Flutter Analytics',
        analytics: analytics,
        observer: observer,
      ),
    );
  }
}
class FlutterAnalyticsHome extends StatefulWidget {
  final String title;
  final FirebaseAnalytics analytics;
  final FirebaseAnalyticsObserver observer;
  FlutterAnalyticsHome({
    Key key,
    this.title,
    this.analytics,
    this.observer,
  }) : super(key: key);
  @override
  _FlutterAnalyticsHomeState createState() => _FlutterAnalyticsHomeState();
}
class _FlutterAnalyticsHomeState extends State<FlutterAnalyticsHome> {
  FirebaseAnalytics _analytics;
  @override
  void initState() {
    /// initializing data to local variable [_analytics] for Firebase Analytics
    /// that we made before for local use
    _analytics = widget.analytics;
    //// below three events are related to user which we are
    //// sending to Firebase Analytics
    _setUserIdInAnalytics();
    _setUserPropertyInAnalytics();
    _currentScreen();
    super.initState();
  }
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colors.white,
      appBar: AppBar(
        title: Center(
          child: Text(widget.title),
        ),
      ),
      body: Padding(
        padding: const EdgeInsets.all(16.0),
        child: ListView(
          shrinkWrap: true,
          children: <Widget>[
            SizedBox(
              height: 16,
            ),
            SingleItemTile(
              itemName: 'Carrot',
              analytics: _analytics,
              quantity: 1,
              price: '100Rs',
            ),
            SizedBox(
              height: 16,
            ),
            SingleItemTile(
              itemName: 'Baby Carrot',
              analytics: _analytics,
              quantity: .5,
              price: '50Rs',
            ),
            SizedBox(
              height: 16,
            ),
          ],
        ),
      ),
    );
  }
  //// to create a unique user identifier for Analytics
  //// send user id(if you app has)
  Future<void> _setUserIdInAnalytics() async {
    await _analytics.setUserId('alksj39hnfn49skvnghqwp40sm');
  }
  //// sending user related field to Analytics
  /// below [name] is the name of the user property to set
  /// [value] is the values of that property
  Future<void> _setUserPropertyInAnalytics() async {
    await _analytics.setUserProperty(
      name: 'email',
      value: '[email protected]',
    );
  }
  /// Setting the current Screen of the app in [screenName]
  /// and sending back to Analytics
  Future<void> _currentScreen() async {
    await _analytics.setCurrentScreen(
      screenName: 'FlutterAnalyticsHome',
      screenClassOverride: 'FlutterAnalyticsHome',
    );
  }
}

Reference

Below are the download links:

No. Link
1. Download code
2. Follow code author

Leave a Reply