Flutter数据分析插件firebase_analytics的使用

发布于 1周前 作者 yuanlaile 来自 Flutter

Flutter数据分析插件firebase_analytics的使用

Firebase Analytics Plugin for Flutter

Flutter插件用于使用Firebase Analytics API。要了解更多关于Firebase Analytics的信息,请访问Firebase官网

pub package

Getting Started

要开始使用Flutter的Firebase Analytics,请参考官方文档

Usage

要使用此插件,请参阅Analytics 使用文档

Issues and feedback

请在我们的issue tracker中提交与FlutterFire相关的特定问题、错误或功能请求。 对于不是特定于FlutterFire的插件问题,可以在Flutter issue tracker中提交。 如需贡献代码修改,请查看我们的贡献指南,并打开一个pull request

示例代码

下面是一个完整的示例demo,演示了如何使用firebase_analytics插件来发送自定义事件、设置用户ID、控制分析数据收集等操作。

// Copyright 2017 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

import 'dart:async';

import 'package:firebase_analytics/firebase_analytics.dart';
import 'package:firebase_core/firebase_core.dart';
import 'package:flutter/material.dart';
import 'firebase_options.dart';
import 'tabs_page.dart';

Future<void> main() async {
  WidgetsFlutterBinding.ensureInitialized();
  await Firebase.initializeApp(
    options: DefaultFirebaseOptions.currentPlatform,
  );
  runApp(const MyApp());
}

class MyApp extends StatelessWidget {
  const MyApp({Key? key}) : super(key: key);

  static FirebaseAnalytics analytics = FirebaseAnalytics.instance;
  static FirebaseAnalyticsObserver observer =
      FirebaseAnalyticsObserver(analytics: analytics);

  @override
  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 MyHomePage extends StatefulWidget {
  MyHomePage({
    Key? key,
    required this.title,
    required this.analytics,
    required this.observer,
  }) : super(key: key);

  final String title;
  final FirebaseAnalytics analytics;
  final FirebaseAnalyticsObserver observer;

  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  String _message = '';

  void setMessage(String message) {
    setState(() {
      _message = message;
    });
  }

  Future<void> _setDefaultEventParameters() async {
    if (kIsWeb) {
      setMessage(
        '"setDefaultEventParameters()" is not supported on web platform',
      );
    } else {
      // Only strings, numbers & null (longs & doubles for android, ints and doubles for iOS) are supported for default event parameters:
      await widget.analytics.setDefaultEventParameters(<String, dynamic>{
        'string': 'string',
        'int': 42,
        'long': 12345678910,
        'double': 42.0,
        'bool': true.toString(),
      });
      setMessage('setDefaultEventParameters succeeded');
    }
  }

  Future<void> _sendAnalyticsEvent() async {
    await widget.analytics.logEvent(
      name: 'test_event',
      parameters: <String, Object>{
        'string': 'string',
        'int': 42,
        'long': 12345678910,
        'double': 42.0,
        'bool': true.toString(),
      },
    );

    setMessage('logEvent succeeded');
  }

  Future<void> _testSetUserId() async {
    await widget.analytics.setUserId(id: 'some-user');
    setMessage('setUserId succeeded');
  }

  Future<void> _testSetAnalyticsCollectionEnabled() async {
    await widget.analytics.setAnalyticsCollectionEnabled(false);
    await widget.analytics.setAnalyticsCollectionEnabled(true);
    setMessage('setAnalyticsCollectionEnabled succeeded');
  }

  Future<void> _testSetSessionTimeoutDuration() async {
    await widget.analytics
        .setSessionTimeoutDuration(const Duration(milliseconds: 20000));
    setMessage('setSessionTimeoutDuration succeeded');
  }

  Future<void> _testSetUserProperty() async {
    await widget.analytics.setUserProperty(name: 'regular', value: 'indeed');
    setMessage('setUserProperty succeeded');
  }

  Future<void> _testSetConsent() async {
    await widget.analytics.setConsent(
      adStorageConsentGranted: true,
      adUserDataConsentGranted: true,
      adPersonalizationSignalsConsentGranted: true,
    );
    setMessage('setConsent succeeded');
  }

  Future<void> _testAppInstanceId() async {
    String? id = await widget.analytics.appInstanceId;
    if (id != null) {
      setMessage('appInstanceId succeeded: $id');
    } else {
      setMessage('appInstanceId failed, consent declined');
    }
  }

  Future<void> _testResetAnalyticsData() async {
    await widget.analytics.resetAnalyticsData();
    setMessage('resetAnalyticsData succeeded');
  }

  Future<void> _testInitiateOnDeviceConversionMeasurement() async {
    await widget.analytics
        .initiateOnDeviceConversionMeasurementWithEmailAddress('test@mail.com');
    setMessage('initiateOnDeviceConversionMeasurement succeeded');
  }

  AnalyticsEventItem itemCreator() {
    return AnalyticsEventItem(
      affiliation: 'affil',
      coupon: 'coup',
      creativeName: 'creativeName',
      creativeSlot: 'creativeSlot',
      discount: 2.22,
      index: 3,
      itemBrand: 'itemBrand',
      itemCategory: 'itemCategory',
      itemCategory2: 'itemCategory2',
      itemCategory3: 'itemCategory3',
      itemCategory4: 'itemCategory4',
      itemCategory5: 'itemCategory5',
      itemId: 'itemId',
      itemListId: 'itemListId',
      itemListName: 'itemListName',
      itemName: 'itemName',
      itemVariant: 'itemVariant',
      locationId: 'locationId',
      price: 9.99,
      currency: 'USD',
      promotionId: 'promotionId',
      promotionName: 'promotionName',
      quantity: 1,
    );
  }

  Future<void> _testAllEventTypes() async {
    await widget.analytics.logAddPaymentInfo();
    await widget.analytics.logAddToCart(
      currency: 'USD',
      value: 123,
      items: [itemCreator(), itemCreator()],
    );
    await widget.analytics.logAddToWishlist();
    await widget.analytics.logAppOpen();
    await widget.analytics.logBeginCheckout(
      value: 123,
      currency: 'USD',
      items: [itemCreator(), itemCreator()],
    );
    await widget.analytics.logCampaignDetails(
      source: 'source',
      medium: 'medium',
      campaign: 'campaign',
      term: 'term',
      content: 'content',
      aclid: 'aclid',
      cp1: 'cp1',
    );
    await widget.analytics.logEarnVirtualCurrency(
      virtualCurrencyName: 'bitcoin',
      value: 345.66,
    );

    await widget.analytics.logGenerateLead(
      currency: 'USD',
      value: 123.45,
    );
    await widget.analytics.logJoinGroup(
      groupId: 'test group id',
    );
    await widget.analytics.logLevelUp(
      level: 5,
      character: 'witch doctor',
    );
    await widget.analytics.logLogin(loginMethod: 'login');
    await widget.analytics.logPostScore(
      score: 1000000,
      level: 70,
      character: 'tiefling cleric',
    );
    await widget.analytics.logPurchase(currency: 'USD', transactionId: 'transaction-id');
    await widget.analytics.logSearch(
      searchTerm: 'hotel',
      numberOfNights: 2,
      numberOfRooms: 1,
      numberOfPassengers: 3,
      origin: 'test origin',
      destination: 'test destination',
      startDate: '2015-09-14',
      endDate: '2015-09-16',
      travelClass: 'test travel class',
    );
    await widget.analytics.logSelectContent(
      contentType: 'test content type',
      itemId: 'test item id',
    );
    await widget.analytics.logSelectPromotion(
      creativeName: 'promotion name',
      creativeSlot: 'promotion slot',
      items: [itemCreator()],
      locationId: 'United States',
    );
    await widget.analytics.logSelectItem(
      items: [itemCreator(), itemCreator()],
      itemListName: 't-shirt',
      itemListId: '1234',
    );
    await widget.analytics.logScreenView(
      screenName: 'tabs-page',
    );
    await widget.analytics.logViewCart(
      currency: 'USD',
      value: 123,
      items: [itemCreator(), itemCreator()],
    );
    await widget.analytics.logShare(
      contentType: 'test content type',
      itemId: 'test item id',
      method: 'facebook',
    );
    await widget.analytics.logSignUp(
      signUpMethod: 'test sign up method',
    );
    await widget.analytics.logSpendVirtualCurrency(
      itemName: 'test item name',
      virtualCurrencyName: 'bitcoin',
      value: 34,
    );
    await widget.analytics.logViewPromotion(
      creativeName: 'promotion name',
      creativeSlot: 'promotion slot',
      items: [itemCreator()],
      locationId: 'United States',
      promotionId: '1234',
      promotionName: 'big sale',
    );
    await widget.analytics.logRefund(
      currency: 'USD',
      value: 123,
      items: [itemCreator(), itemCreator()],
    );
    await widget.analytics.logTutorialBegin();
    await widget.analytics.logTutorialComplete();
    await widget.analytics.logUnlockAchievement(id: 'all Firebase API covered');
    await widget.analytics.logViewItem(
      currency: 'usd',
      value: 1000,
      items: [itemCreator()],
    );
    await widget.analytics.logViewItemList(
      itemListId: 't-shirt-4321',
      itemListName: 'green t-shirt',
      items: [itemCreator()],
    );
    await widget.analytics.logViewSearchResults(
      searchTerm: 'test search term',
    );
    setMessage('All standard events logged successfully');
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(widget.title),
      ),
      body: Center(
        child: Column(
          children: <Widget>[
            MaterialButton(
              onPressed: _sendAnalyticsEvent,
              child: const Text('Test logEvent'),
            ),
            MaterialButton(
              onPressed: _testAllEventTypes,
              child: const Text('Test standard event types'),
            ),
            MaterialButton(
              onPressed: _testSetUserId,
              child: const Text('Test setUserId'),
            ),
            MaterialButton(
              onPressed: _testSetAnalyticsCollectionEnabled,
              child: const Text('Test setAnalyticsCollectionEnabled'),
            ),
            MaterialButton(
              onPressed: _testSetSessionTimeoutDuration,
              child: const Text('Test setSessionTimeoutDuration'),
            ),
            MaterialButton(
              onPressed: _testSetUserProperty,
              child: const Text('Test setUserProperty'),
            ),
            MaterialButton(
              onPressed: _testAppInstanceId,
              child: const Text('Test appInstanceId'),
            ),
            MaterialButton(
              onPressed: _testResetAnalyticsData,
              child: const Text('Test resetAnalyticsData'),
            ),
            MaterialButton(
              onPressed: _testSetConsent,
              child: const Text('Test setConsent'),
            ),
            MaterialButton(
              onPressed: _setDefaultEventParameters,
              child: const Text('Test setDefaultEventParameters'),
            ),
            MaterialButton(
              onPressed: _testInitiateOnDeviceConversionMeasurement,
              child: const Text('Test initiateOnDeviceConversionMeasurement'),
            ),
            Text(
              _message,
              style: const TextStyle(color: Color.fromARGB(255, 0, 155, 0)),
            ),
          ],
        ),
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: () {
          Navigator.of(context).push(
            MaterialPageRoute<TabsPage>(
              settings: const RouteSettings(name: TabsPage.routeName),
              builder: (BuildContext context) {
                return TabsPage(widget.observer);
              },
            ),
          );
        },
        child: const Icon(Icons.tab),
      ),
    );
  }
}

关键点解释

  1. 初始化Firebase:在应用启动时初始化Firebase,并配置Firebase Analytics。
  2. 发送自定义事件:通过logEvent方法发送自定义事件,可以包含参数。
  3. 设置用户ID:通过setUserId方法为当前用户设置唯一标识符。
  4. 控制分析数据收集:通过setAnalyticsCollectionEnabled方法启用或禁用分析数据收集。
  5. 设置会话超时时间:通过setSessionTimeoutDuration方法设置会话超时时间。
  6. 设置用户属性:通过setUserProperty方法设置用户的持久化属性。
  7. 获取应用实例ID:通过appInstanceId方法获取应用实例ID。
  8. 重置分析数据:通过resetAnalyticsData方法重置所有分析数据。
  9. 设置用户同意:通过setConsent方法设置用户对广告存储和个性化信号的同意状态。
  10. 设置默认事件参数:通过setDefaultEventParameters方法设置默认事件参数。
  11. 设备转换测量:通过initiateOnDeviceConversionMeasurementWithEmailAddress方法发起设备转换测量。

这个示例展示了如何在Flutter应用中集成和使用Firebase Analytics插件,帮助开发者更好地理解和使用该插件的功能。


更多关于Flutter数据分析插件firebase_analytics的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html

1 回复

更多关于Flutter数据分析插件firebase_analytics的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html


当然,下面是一个关于如何在Flutter项目中使用Firebase Analytics插件(firebase_analytics)的示例代码案例。这个示例将展示如何初始化Firebase Analytics、设置用户属性、记录事件以及获取当前的Firebase Analytics实例。

1. 添加依赖

首先,你需要在你的pubspec.yaml文件中添加firebase_analytics依赖:

dependencies:
  flutter:
    sdk: flutter
  firebase_core: ^1.10.0  # Firebase Core 是必需的,用于初始化 Firebase 应用
  firebase_analytics: ^9.0.0  # 添加 Firebase Analytics 依赖

2. 初始化Firebase

在你的main.dart文件中,你需要初始化Firebase应用并配置Firebase Analytics。

import 'package:flutter/material.dart';
import 'package:firebase_core/firebase_core.dart';
import 'package:firebase_analytics/firebase_analytics.dart';

void main() async {
  WidgetsFlutterBinding.ensureInitialized();
  // 初始化 Firebase
  await Firebase.initializeApp();

  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: Text('Firebase Analytics Example'),
        ),
        body: AnalyticsScreen(),
      ),
    );
  }
}

3. 使用Firebase Analytics

创建一个新的Dart文件(例如analytics_screen.dart),并在其中使用Firebase Analytics记录事件和设置用户属性。

import 'package:flutter/material.dart';
import 'package:firebase_analytics/firebase_analytics.dart';

class AnalyticsScreen extends StatelessWidget {
  final FirebaseAnalytics analytics = FirebaseAnalytics.instance;

  @override
  Widget build(BuildContext context) {
    return Padding(
      padding: const EdgeInsets.all(16.0),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: <Widget>[
          Text(
            'Firebase Analytics Example',
            style: TextStyle(fontSize: 24),
          ),
          SizedBox(height: 16),
          ElevatedButton(
            onPressed: () {
              _logEvent();
            },
            child: Text('Log Event'),
          ),
          SizedBox(height: 16),
          ElevatedButton(
            onPressed: () {
              _setUserProperty();
            },
            child: Text('Set User Property'),
          ),
        ],
      ),
    );
  }

  void _logEvent() {
    // 定义一个自定义事件
    analytics.logEvent(
      name: 'select_content',
      parameters: <String, dynamic>{
        'content_type': 'image',
        'item_id': '1234',
      },
    );
    print('Event logged: select_content');
  }

  void _setUserProperty() {
    // 设置用户属性
    analytics.setUserProperty(
      name: 'favorite_food',
      value: 'pizza',
    );
    print('User property set: favorite_food = pizza');
  }
}

4. 运行应用

确保你已经在Firebase控制台中为你的应用配置了Firebase Analytics,并且你的应用已经成功连接到了Firebase项目。然后运行你的Flutter应用:

flutter run

5. 验证数据

在Firebase控制台中,导航到你的项目,然后进入Analytics部分。你应该能够看到从你的应用中记录的事件和用户属性。

这个示例展示了如何使用firebase_analytics插件在Flutter应用中记录自定义事件和设置用户属性。根据你的需求,你可以进一步扩展这些功能,例如记录更多类型的事件或设置更多用户属性。

回到顶部