How to add google tag manager in flutter app?

Member

by elliott , in category: SEO Tools , a year ago

How to add google tag manager in flutter app?

Facebook Twitter LinkedIn Telegram Whatsapp Pocket

1 answer

by cameron_walter , a year ago

@elliott 

To add Google Tag Manager to a Flutter app, you can follow these steps:

  1. Create a Google Tag Manager account: Go to the Google Tag Manager website and sign in with your Google account. Create a new account if you don't have one already.
  2. Create a container: After you have logged in to your account, create a new container by providing a name and a target platform for the container.
  3. Obtain the container ID: After creating the container, you will be provided with a container ID. Make note of this ID as it will be needed in the next steps.
  4. Add the dependencies: Open your Flutter app's pubspec.yaml file and add the following dependencies:
1
2
3
4
dependencies:
  google_tag_manager: any
  firebase_core: ^1.2.0
  firebase_analytics: ^8.1.2


  1. Fetch the packages: In your terminal, navigate to your Flutter app's root directory and run the command flutter pub get to fetch the added dependencies.
  2. Initialize Google Tag Manager: In your app's main.dart file, import the required packages by adding the following import statements:
1
2
3
import 'package:google_tag_manager/google_tag_manager.dart';
import 'package:firebase_core/firebase_core.dart';
import 'package:firebase_analytics/firebase_analytics.dart';


After that, initialize Firebase and Google Tag Manager in the main() function as follows:

1
2
3
4
5
6
7
void main() async {
  WidgetsFlutterBinding.ensureInitialized();
  await Firebase.initializeApp();
  FirebaseAnalytics analytics = FirebaseAnalytics();
  GoogleTagManager().pushDataLayerEvent(<String, dynamic>{});
  runApp(MyApp(analytics));
}


  1. Set up container constants: In the same main.dart file, define the container constants and initialize the Google Tag Manager instance. Replace YOUR_CONTAINER_ID with your actual container ID obtained in Step 3.
1
2
3
4
5
6
7
const containerId = 'YOUR_CONTAINER_ID';

GoogleTagManager googleTagManager = GoogleTagManager(
  containerId,
  Logger(),
  <String, Function>{} // optional data layer callbacks
);


  1. Push data layer events: You can push events to the data layer of Google Tag Manager by calling the pushDataLayerEvent() method. For example, you can push an event when a button is pressed:
1
2
3
4
5
6
7
8
9
FlatButton(
  onPressed: () {
    googleTagManager.pushDataLayerEvent(<String, dynamic>{
      'event': 'button_click',
      'button_text': 'Click me',
    });
  },
  child: Text('Click Me'),
),


That's it! You have successfully added Google Tag Manager to your Flutter app. You can now use the Tag Manager interface to add tags, triggers, and variables to track and analyze user interactions in your app.