ZXERSTON
ZXERSTON

Reputation: 323

How to track google analytics event in a flutter widget?

I am looking to track how many times a button/expansion tile is clicked.

I tried reading the docs but still can't get the concept of it. In the flutter fire docs, it stated to log custom events by calling the logEvent method hERE.

await FirebaseAnalytics.instance
  .logEvent(
    name: 'view_product',
    parameters: {
      'product_id': 1234,
    }
  ); 

However, what if it is an expansion tile widget (like the code below) or even a button? How do I track the event whenever a user pressed the expansion tile widget/button in flutter and the event will be tracked in my Google Analytics? (I have already set up firebase and google analytics packages, just struggling on the code part)

ExpansionTile(
                title: RichText(
                  textAlign: TextAlign.justify,
                  text: TextSpan(
                    children: <TextSpan>[
                      TextSpan(
                        text: "Diploma in Business | ",
                        style: TextStyle(color: Colors.black),
                      ),
                      TextSpan(
                        text: "Taylor\u0027s",
                        style: TextStyle(
                            color: Colors.black, fontWeight: FontWeight.bold),
                      ),
                    ],
                  ),
                ),
              ),

Appreciate any help or guidance I can get, thank you in advance!

Upvotes: 0

Views: 3296

Answers (2)

Fahmida
Fahmida

Reputation: 1220

First of all make your ExpansionTile clickable. Wrap your ExpansionTile with Inkwell and its onTap property call logevent function

Inkwell(
 onTap:(){
   sendAnalyticsEvent("User clicked expansionTile");
},
child : ExpansionTile(
 //write your expansion tile
 ),
);

And this the analytics custom event function.

 final FirebaseAnalytics _analytics = FirebaseAnalytics();
 Future sendAnalyticsEvent(
     {String eventName, String? clickevent}) async {
      await _analytics.logEvent(
      name: '${eventName}',
      parameters: <String, dynamic>{
        'clickEvent': clickevent
     },
   );
 }

Call this function like this

sendAnalyticsEvent( eventName : "expansionTile_one", clickevent : "User clicked first expansionTile")

sendAnalyticsEvent( eventName : "expansionTile_two", clickevent : "User clicked 2nd expansionTile")

Check this click event in analytics debugView.

Upvotes: 1

Vinicius Ribeiro
Vinicius Ribeiro

Reputation: 1

Inside your ExpansionTile, you can use:

onExpansionChanged: (value){
    sendAnalyticsEvent("User clicked expansionTile");
}

Upvotes: 0

Related Questions