Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set Firebase Analytics custom events in Flutter without passing 'analytics/observer' object in each screen

I'm setting up Firebase Analytics Package for my Flutter project. The sample provided in the library passes the analytics object for tracking events and observer for tracking the tab changes.

class MyApp extends StatelessWidget {
 ...
Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Firebase Analytics Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      navigatorObservers: <NavigatorObserver>[observer],
      home: MyHomePage(
        title: 'Firebase Analytics Demo',
        analytics: analytics,
        observer: observer,
      ),
    );
  }
}

...

class _MyHomePageState extends State<MyHomePage> {
...
Future<void> _sendAnalyticsEvent() async {
    await analytics.logEvent(
      name: 'test_event',
      parameters: <String, dynamic>{
        'string': 'string',
        'int': 42,
        'long': 12345678910,
        'double': 42.0,
        'bool': true,
      },
    );
    setMessage('logEvent succeeded');
  }
...
}

My app consists of a lot of screens where the state is managed via a Bloc package. Passing these objects from mainScreen all the way down the tree where the events are happening would not be good.

Is there a way to access them without passing them around the widget tree. Or would it work if I create a new object of the class FirebaseAnalytics and use the generated object to set an event?

static FirebaseAnalytics analytics = FirebaseAnalytics();

Or should I use Flutter_Bloc as a central place to log and set my Flutter Events?

like image 383
Mayur Dhurpate Avatar asked Jul 12 '19 09:07

Mayur Dhurpate


3 Answers

You can use the provider package to 'provide' both your analytics and observer down your widget tree.

class MyApp extends StatelessWidget {
  static FirebaseAnalytics analytics = FirebaseAnalytics();
  static FirebaseAnalyticsObserver observer =
      FirebaseAnalyticsObserver(analytics: analytics);

  @override
  Widget build(BuildContext context) {
    return MultiProvider(
        providers: [
            Provider<FirebaseAnalytics>.value(value: analytics),
            Provider<FirebaseAnalyticsObserver>.value(value: observer),
        ],
        child: MaterialApp(
            title: 'Firebase Analytics Demo',
            theme: ThemeData(
                primarySwatch: Colors.blue,
            ),
            navigatorObservers: <NavigatorObserver>[observer],
            home: MyHomePage(
                title: 'Firebase Analytics Demo',
            ),
        ),
    ); 
  }
}

Then in any of your child widgets...

Future<void> _sendAnalyticsEvent() async {
    FirebaseAnalytics analytics = Provider.of<FirebaseAnalytics>(context);
    await analytics.logEvent(
      name: 'test_event',
      parameters: <String, dynamic>{
        'string': 'string',
        'int': 42,
        'long': 12345678910,
        'double': 42.0,
        'bool': true,
      },
    );
    setMessage('logEvent succeeded');
  }

Now you don't need to pass your Firebase instances to the widget constructors.

like image 122
Martyns Avatar answered Nov 09 '22 13:11

Martyns


Besides using provider or a global class with static parameters, another option is to use services with the GetIt package.

Just create a class that hold's the analytics and observer. E.g. like this:

class AnalyticsService {
  final FirebaseAnalytics _analytics = FirebaseAnalytics();

  FirebaseAnalyticsObserver getAnalyticsObserver() => FirebaseAnalyticsObserver(analytics: _analytics);

  Future logScreens({@required String name}) async {
    await _analytics.setCurrentScreen(screenName: name);
  }

  ... // implement the events you want to track
}

Now create a locator and register the class as a lazy singleton:

GetIt locator = GetIt.instance;

setupServiceLocator() {
  locator.registerLazySingleton<AnalyticsService>(() => AnalyticsService());
}

Make the locator accessable:

void main() async {
  WidgetsFlutterBinding.ensureInitialized();
  setupServiceLocator();
  runApp(MyApp());
}

Now you can access the service from everywhere in your app by calling the locator. For example:

return MaterialApp(
  debugShowCheckedModeBanner: false,
  title: 'Demo',
  theme: themeData,
  initialRoute: SplashScreen.id,
  routes: routes,
  navigatorObservers: [
    // Access the observer
    locator<AnalyticsService>().getAnalyticsObserver(),
  ],
);

}

or

 onTap: () {
   locator<AnalyticsService>().logScreens(name: DetailsScreen.id);
 }
like image 7
Matthias Avatar answered Nov 09 '22 11:11

Matthias


It is also possible to create a file with all of your global instances. e.g: file: globals.dart in your lib directory.

Content of the file:

class Global {
    static final FirebaseAnalytics analytics = FirebaseAnalytics();
}

Then to use it:

Global.analytics.logEvent(...)
like image 6
Ivan Avatar answered Nov 09 '22 11:11

Ivan