How to connect Google Analytics in a Flutter Web App?

Viewed 3959
3 Answers

You need to add dependency for analytics in android/app/build.gradle, implementation 'com.google.firebase:firebase-analytics'. If you need to log events then you might want to use the package https://pub.dev/packages/firebase_analytics. Otherwise just adding above dependency is sufficient.

If you are looking for a simple approach more than using a package, then you can follow the below solution.

Add the following app.js in web/ directory

// file: /web/app.js
function sendNavigation(location) {
    // Replace UA-XXXXXXXXX-X with Google Analytics ID
    gtag('config', 'UA-XXXXXXXXX-X', { page_path: location });
}

Add the script into web/index.html by adding

<head>
  <!--...-->
  <script src="app.js" defer></script>
</head>

Now, you can simply call

js.context.callMethod('sendNavigation', ['routePath']);

when the user navigates to the page in dart file.

You can learn more about this from a blog I wrote - link

Related