Flutter性能监控与分析插件fullstory_flutter的使用

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

Flutter性能监控与分析插件fullstory_flutter的使用

Fullstory Flutter Package

Fullstory Flutter 插件允许您在Flutter应用中访问Fullstory Native Mobile SDK。此插件旨在与Fullstory for Mobile Apps配合使用。

注意:这是一个预览版本,发布1.0.0之前可能会有一些重大更改。

Quick Links

What’s supported

大多数非视觉Fullstory API都支持:

  • FS.event(String name, [Map<String, Object?> properties = const {}])
  • FS.page(String pageName, [Map<String, Object?>? pageVars])FSPage
  • FS.log({FSLogLevel level = FSLogLevel.info, required String message})
  • FS.identify(String uid, [Map<String, Object?>? userVars])
  • FS.setUserVars(Map<String, Object?> userVars)
  • FS.anonymize()
  • FS.shutdown()
  • FS.restart()
  • FS.setStatusListener(FSStatusListener? listener)
  • FS.getCurrentSessionFuture<String?>
  • FS.getCurrentSessionURL({bool now = false})Future<String?>
  • FS.fsVersionFuture<String?>
  • FS.resetIdleTimer()

视觉会话回放目前不支持,但计划在未来版本中添加。

Getting Started

查看Fullstory for Flutter Mobile Apps入门指南

此外,请参阅我们的示例应用以获取工作API使用示例。


示例代码

import 'package:flutter/material.dart';
import 'package:fullstory_flutter/fs.dart';

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

  @override
  State<CaptureStatus> createState() => _CaptureStatusState();
}

class _CaptureStatusState extends State<CaptureStatus> with FSStatusListener {
  var status = "Loading...";
  var url = "";
  var id = "";
  var urlNow = "Press button to update";

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

    // grab the current session URL & ID in case it has already started
    FS.getCurrentSessionURL().then((url) =&gt; setState(() {
          if (url != null) {
            // if there is a url, we know the session started
            this.url = url;
            status = "Started";
          }
        }));
    FS.currentSession.then((id) =&gt; setState(() {
          this.id = id ?? "";
        }));

    // set the status listener to handle future changes
    FS.setStatusListener(this);
  }

  @override
  void dispose() {
    super.dispose();
    // clear the current status listener (there can be only one!)
    FS.setStatusListener(null);
  }

  // This comes from FSStatusListener - the default implementation is a no-op
  @override
  void onFSSession(String url) {
    setState(() {
      status = "Started";
      this.url = url;
      FS.currentSession.then((id) =&gt; setState(() {
            this.id = id ?? "";
          }));
    });
  }

  @override
  Widget build(BuildContext context) {
    return Column(
      children: [
        Wrap(
          children: [
            TextButton(
                onPressed: () {
                  FS.shutdown();
                  // manually do this one since only the iOS SDK has a callback for it
                  setState(() {
                    status = "Shutdown";
                    url = "";
                    id = "";
                  });
                },
                child: const Text("Shutdown")),
            const TextButton(onPressed: FS.restart, child: Text("Restart")),
            TextButton(
                onPressed: () {
                  FS.getCurrentSessionURL(now: true).then((url) =&gt; setState(() {
                        urlNow = url ?? "";
                      }));
                },
                child: const Text("Update Timestamped URL"))
          ],
        ),
        SelectableText("Status: $status\nURL: $url\nNow: $urlNow\nID: $id"),
      ],
    );
  }
}
import 'package:flutter/material.dart';
import 'package:fullstory_flutter/fs.dart';

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

  @override
  Widget build(BuildContext context) {
    return Wrap(
      children: [
        TextButton(
          onPressed: () =&gt; FS.event("Name-only event"),
          child: const Text("Name-only event"),
        ),
        TextButton(
          onPressed: () =&gt; FS.event("Many properties event", {
            "string_val": "a string value",
            "int_val": 42,
            "double_val": 0.1,
            "bool_val": true,
            "null_val": null,
            "list_val": [1, 2, 3],

            // in playback, this is displayed as:
            // map_val.nested_map.val_bool: true
            // map_val.nested_string_str: nested string
            "map_val": {
              "nested_string": "nested string",
              "nested_map": {"val": true},
            },
            //"mixed_list_val": [4, "a", false], // not supported, error in playback
          }),
          child: const Text("Many properties event"),
        ),
        TextButton(
          onPressed: () =&gt; FS.event('Order Completed', {
            'orderId': '23f3er3d',
            'products': [
              {'productId': '9v87h4f8', 'price': 20.00, 'quantity': 0.75},
              {'productId': '4738b43z', 'price': 12.87, 'quantity': 6},
            ],
          }),
          child: const Text('Order Completed event'),
        )
      ],
    );
  }
}
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:fullstory_flutter/fs.dart';

class FSVersion extends StatefulWidget {
  const FSVersion({super.key});
  @override
  State&lt;FSVersion&gt; createState() =&gt; _FSVersionState();
}

class _FSVersionState extends State&lt;FSVersion&gt; {
  String fsVersion = 'Unknown';
  @override
  void initState() {
    super.initState();
    initPlatformState();
  }

  Future&lt;void&gt; initPlatformState() async {
    String fsVersion;
    try {
      fsVersion = await FS.fsVersion ?? 'Unknown Fullstory version';
    } on PlatformException {
      fsVersion = 'Failed to get Fullstory version.';
    }

    if (!mounted) return;

    setState(() {
      this.fsVersion = fsVersion;
    });
  }

  @override
  Widget build(BuildContext context) {
    return Text('Fullstory version: $fsVersion\n');
  }
}

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

1 回复

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


当然,以下是如何在Flutter项目中集成和使用fullstory_flutter插件进行性能监控与分析的代码案例。

1. 添加依赖

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

dependencies:
  flutter:
    sdk: flutter
  fullstory_flutter: ^x.y.z  # 请替换为最新版本号

然后运行flutter pub get来获取依赖。

2. 初始化FullStory

在你的Flutter应用的入口文件(通常是main.dart)中,初始化FullStory客户端。

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

void main() {
  // 替换为你的FullStory组织ID
  const String fullStoryOrgId = 'YOUR_FULLSTORY_ORG_ID';

  // 初始化FullStory
  FullStory.instance.init(fullStoryOrgId);

  runApp(MyApp());
}

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

class MyHomePage extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Flutter FullStory Demo'),
      ),
      body: Center(
        child: Text('Hello, FullStory!'),
      ),
    );
  }
}

3. 自定义事件记录

你可以在任何地方记录自定义事件,以便更好地进行性能监控与分析。

import 'package:fullstory_flutter/fullstory_flutter.dart';

// 假设在某个按钮点击事件中
void _onButtonPressed() {
  // 记录自定义事件
  FullStory.instance.event('button_clicked', {
    'button_label': 'Submit',
    'user_id': '12345',  // 可选的,记录用户ID
  });

  // 其他业务逻辑
}

4. 屏幕视图追踪

FullStory通常会自动追踪屏幕视图,但你也可以手动追踪,如果需要的话。

import 'package:fullstory_flutter/fullstory_flutter.dart';

void _onSomeScreenVisible() {
  // 手动追踪屏幕视图
  FullStory.instance.screen('SomeScreenName');
}

5. 用户标识

你可以设置用户标识,以便更好地识别和分析用户行为。

import 'package:fullstory_flutter/fullstory_flutter.dart';

void _setUserIdentity(String userId) {
  FullStory.instance.identify(userId: userId, traits: {
    'name': 'John Doe',
    'email': 'john.doe@example.com',
    // 其他用户属性
  });
}

6. 清理与退出

在应用退出或用户注销时,可以清理FullStory会话。

import 'package:fullstory_flutter/fullstory_flutter.dart';

void _onLogout() {
  // 清理FullStory会话
  FullStory.instance.shutdown();

  // 其他注销逻辑
}

总结

以上代码展示了如何在Flutter项目中集成fullstory_flutter插件,并进行基本的性能监控与分析操作。请确保替换YOUR_FULLSTORY_ORG_ID为你的实际FullStory组织ID,并根据你的应用需求调整事件记录和用户标识逻辑。

希望这能帮助你更好地进行Flutter应用的性能监控与分析。

回到顶部