Flutter性能监控插件firebase_performance的使用

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

Flutter性能监控插件firebase_performance的使用

Firebase Performance Plugin for Flutter

一个用于Flutter应用程序的插件,以使用Firebase Performance API。要了解更多关于Firebase Performance的信息,请访问Firebase网站

Getting Started

开始使用Flutter的Firebase Performance,请参阅文档

Usage

使用此插件,请访问Firebase Performance Usage 文档

Issues and feedback

请在我们的issue tracker中提交与FlutterFire相关的问题、错误或功能请求。

非特定于FlutterFire的插件问题可以在Flutter issue tracker中提交。

如果您想为此插件贡献更改,请查看我们的贡献指南,并打开一个pull request

示例代码

下面是一个完整的示例demo,展示了如何在Flutter应用中使用firebase_performance插件来监控应用性能。

// Copyright 2021 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_core/firebase_core.dart';
import 'package:firebase_performance/firebase_performance.dart';
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;

import 'firebase_options.dart';

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

class MyApp extends StatefulWidget {
  @override
  _MyAppState createState() => _MyAppState();
}

class _MetricHttpClient extends http.BaseClient {
  _MetricHttpClient(this._inner);

  final http.Client _inner;

  @override
  Future<http.StreamedResponse> send(http.BaseRequest request) async {
    // Custom network monitoring is not supported for web.
    // https://firebase.google.com/docs/perf-mon/custom-network-traces?platform=android
    final HttpMetric metric = FirebasePerformance.instance
        .newHttpMetric(request.url.toString(), HttpMethod.Get);

    metric.requestPayloadSize = request.contentLength;
    await metric.start();

    http.StreamedResponse response;
    try {
      response = await _inner.send(request);
      print(
        'Called ${request.url} with custom monitoring, response code: ${response.statusCode}',
      );

      metric.responseContentType = 'text/html';
      metric.httpResponseCode = response.statusCode;
      metric.responsePayloadSize = response.contentLength;

      metric.putAttribute('score', '15');
      metric.putAttribute('to_be_removed', 'should_not_be_logged');
    } finally {
      metric.removeAttribute('to_be_removed');
      await metric.stop();
    }

    final attributes = metric.getAttributes();

    print('Http metric attributes: $attributes.');

    String? score = metric.getAttribute('score');
    print('Http metric score attribute value: $score');

    return response;
  }
}

class _MyAppState extends State<MyApp> {
  FirebasePerformance _performance = FirebasePerformance.instance;
  bool _isPerformanceCollectionEnabled = false;
  String _performanceCollectionMessage =
      'Unknown status of performance collection.';
  bool _trace1HasRan = false;
  bool _trace2HasRan = false;
  bool _customHttpMetricHasRan = false;

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

  Future<void> _togglePerformanceCollection() async {
    // No-op for web.
    await _performance
        .setPerformanceCollectionEnabled(!_isPerformanceCollectionEnabled);

    // Always true for web.
    final bool isEnabled = await _performance.isPerformanceCollectionEnabled();
    setState(() {
      _isPerformanceCollectionEnabled = isEnabled;
      _performanceCollectionMessage = _isPerformanceCollectionEnabled
          ? 'Performance collection is enabled.'
          : 'Performance collection is disabled.';
    });
  }

  Future<void> _testTrace1() async {
    setState(() {
      _trace1HasRan = false;
    });

    final Trace trace = _performance.newTrace('test_trace_3');
    await trace.start();
    trace.putAttribute('favorite_color', 'blue');
    trace.putAttribute('to_be_removed', 'should_not_be_logged');

    trace.incrementMetric('sum', 200);
    trace.incrementMetric('total', 342);

    trace.removeAttribute('to_be_removed');
    await trace.stop();

    final sum = trace.getMetric('sum');
    print('test_trace_1 sum value: $sum');

    final attributes = trace.getAttributes();
    print('test_trace_1 attributes: $attributes');

    final favoriteColor = trace.getAttribute('favorite_color');
    print('test_trace_1 favorite_color: $favoriteColor');

    setState(() {
      _trace1HasRan = true;
    });
  }

  Future<void> _testTrace2() async {
    setState(() {
      _trace2HasRan = false;
    });

    final Trace trace = FirebasePerformance.instance.newTrace('test_trace_2');
    await trace.start();

    trace.setMetric('sum', 333);
    trace.setMetric('sum_2', 895);
    await trace.stop();

    final sum2 = trace.getMetric('sum');
    print('test_trace_2 sum value: $sum2');

    setState(() {
      _trace2HasRan = true;
    });
  }

  Future<void> _testCustomHttpMetric() async {
    setState(() {
      _customHttpMetricHasRan = false;
    });

    final _MetricHttpClient metricHttpClient = _MetricHttpClient(http.Client());

    final http.Request request = http.Request(
      'SEND',
      Uri.parse('https://www.bbc.co.uk'),
    );

    unawaited(metricHttpClient.send(request));

    setState(() {
      _customHttpMetricHasRan = true;
    });
  }

  Future<void> _testAutomaticHttpMetric() async {
    http.Response response = await http.get(Uri.parse('https://www.facebook.com'));
    print('Called facebook, response code: ${response.statusCode}');
  }

  @override
  Widget build(BuildContext context) {
    const textStyle = TextStyle(color: Colors.lightGreenAccent, fontSize: 25);
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: const Text('Firebase Performance Example'),
        ),
        body: Center(
          child: Column(
            children: <Widget>[
              Text(_performanceCollectionMessage),
              ElevatedButton(
                onPressed: _togglePerformanceCollection,
                child: const Text('Toggle Data Collection'),
              ),
              ElevatedButton(
                onPressed: _testTrace1,
                child: const Text('Run Trace One'),
              ),
              Text(
                _trace1HasRan ? 'Trace Ran!' : '',
                style: textStyle,
              ),
              ElevatedButton(
                onPressed: _testTrace2,
                child: const Text('Run Trace Two'),
              ),
              Text(
                _trace2HasRan ? 'Trace Ran!' : '',
                style: textStyle,
              ),
              ElevatedButton(
                onPressed: _testCustomHttpMetric,
                child: const Text('Run Custom HttpMetric'),
              ),
              Text(
                _customHttpMetricHasRan ? 'Custom HttpMetric Ran!' : '',
                style: textStyle,
              ),
              ElevatedButton(
                onPressed: _testAutomaticHttpMetric,
                child: const Text('Run Automatic HttpMetric'),
              ),
            ],
          ),
        ),
      ),
    );
  }
}

代码说明:

  • 初始化Firebase:在main函数中初始化Firebase。
  • 性能监控:通过FirebasePerformance实例监控应用性能。
  • 自定义HTTP监控:通过扩展http.BaseClient类,添加自定义网络请求监控逻辑。
  • 性能追踪:创建和管理Trace对象,记录应用中的关键操作。
  • UI交互:提供按钮触发不同的性能测试,并显示结果。

以上就是如何在Flutter应用中使用firebase_performance插件进行性能监控的方法。希望这个示例能帮助你更好地理解和使用该插件。


更多关于Flutter性能监控插件firebase_performance的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html

1 回复

更多关于Flutter性能监控插件firebase_performance的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html


当然,关于Flutter性能监控插件firebase_performance的使用,以下是一个详细的代码示例,展示如何集成和使用这个插件来监控应用的性能。

1. 添加依赖

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

dependencies:
  flutter:
    sdk: flutter
  firebase_core: ^1.10.0  # 确保添加firebase_core,因为firebase_performance依赖于它
  firebase_performance: ^0.8.0+3  # 使用最新的稳定版本

2. 配置Firebase

在Firebase控制台中为你的应用创建一个项目,并下载google-services.json文件,将其放置在android/app/目录下。对于iOS,你需要将GoogleService-Info.plist文件放置在ios/Runner/目录下。

3. 初始化Firebase和性能监控

在你的Flutter应用的主入口文件(通常是main.dart)中,初始化Firebase和性能监控:

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

void main() async {
  WidgetsFlutterBinding.ensureInitialized();
  await Firebase.initializeApp();
  final performance = await FirebasePerformance.instance;

  // 启用性能监控(可选,但推荐在开发阶段启用)
  await performance.setPerformanceCollectionEnabled(true);

  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Firebase Performance Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: MyHomePage(),
    );
  }
}

4. 使用性能监控

在应用的逻辑中,你可以使用FirebasePerformance实例来监控特定操作的性能。例如,监控一个按钮点击事件的性能:

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

class MyHomePage extends StatefulWidget {
  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  final performance = FirebasePerformance.instance;

  void _onButtonPressed() async {
    // 创建一个新的trace
    final trace = await performance.newTrace('button_press_trace');

    // 开始trace
    trace.start();

    // 模拟一个耗时操作
    await Future.delayed(Duration(seconds: 2));

    // 结束trace
    trace.stop();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Firebase Performance Demo'),
      ),
      body: Center(
        child: ElevatedButton(
          onPressed: _onButtonPressed,
          child: Text('Press me'),
        ),
      ),
    );
  }
}

5. 查看性能数据

在Firebase控制台中,导航到你的项目,然后进入“Performance”部分,你可以在这里查看和分析应用的性能数据。

注意事项

  • 确保你已经在Firebase控制台中正确配置了应用,并且下载并放置了必要的配置文件。
  • 性能监控数据可能需要一些时间才能在Firebase控制台中显示。
  • 在生产环境中,你可能希望根据条件(如用户同意)来启用或禁用性能监控。

这个示例展示了如何在Flutter应用中使用firebase_performance插件来监控应用的性能。你可以根据需求进一步自定义和扩展这些代码。

回到顶部