I use Google Analytics in Flutter already, how can I also send events to it from native iOS/Android code?

Viewed 173

I use firebase for flutter, where all the dependencies are on pubspec.yaml I would like to send an event to Firebase Analytics for some activities on the native side - Home screen widget, notification received, etc.

Is it possible? FirebaseAnalytics class is not recognized on Android and if I add it to gradle, it might collide with flutter.

1 Answers

Using PlatformChannel is a solution for this case, see platform-channels. Example code (original code from here:

  • Android side:
package com.example.shared;

import android.content.Intent;
import android.os.Bundle;

import androidx.annotation.NonNull;

import io.flutter.plugin.common.MethodChannel;
import io.flutter.embedding.android.FlutterActivity;
import io.flutter.embedding.engine.FlutterEngine;
import io.flutter.plugins.GeneratedPluginRegistrant;

public class MainActivity extends FlutterActivity {

  private static final String CHANNEL = "app.channel.shared.data";
  private String sharedText;

  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    
    sharedText = "Home screen displayed";
  }

  @Override
  public void configureFlutterEngine(@NonNull FlutterEngine flutterEngine) {
      GeneratedPluginRegistrant.registerWith(flutterEngine);

      new MethodChannel(flutterEngine.getDartExecutor().getBinaryMessenger(), CHANNEL)
              .setMethodCallHandler(
                      (call, result) -> {
                          if (call.method.contentEquals("onScreenView")) {
                              result.success(sharedText);
                              sharedText = null;
                          }
                      }
              );
  }

}

  • Flutter side:
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';

void main() {
  runApp(const SampleApp());
}

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

  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Sample Shared App Handler',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: const SampleAppPage(),
    );
  }
}

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

  @override
  State<SampleAppPage> createState() => _SampleAppPageState();
}

class _SampleAppPageState extends State<SampleAppPage> {
  static const platform = MethodChannel('app.channel.shared.data');
  String dataShared = 'No data';

  @override
  void initState() {
    super.initState();
    getSharedText();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(body: Center(child: Text(dataShared)));
  }

  Future<void> getSharedText() async {
    var sharedData = await platform.invokeMethod('onNotificationClicked');
    if (sharedData != null) {
      setState(() {
        dataShared = sharedData;

        // Send data to Firebase Analytics here
      });
    }
  }
}
Related