Flutter应用追踪与分析插件appstrax_services的使用

Flutter应用追踪与分析插件appstrax_services的使用

概述

Appstrax与CodeCapsules合作,提供软件工具和基础设施,以协助开发、托管和管理您的应用程序。


开始使用

要使用可用的服务,需要在内部配置Auth、Database和Storage API的实例。每个实例都会部署一个前端,用于与注册用户、应用数据和上传文件进行交互。

要设置此实例,请先发送电子邮件至info@appstrax.tech,我们将帮助您在此创建、托管和管理Appstrax API:https://codecapsules.io/


安装

appstrax_services添加为项目依赖项:

pub add appstrax_services

初始化

初始化appstrax_services库:

// 导入服务库
import 'package:appstrax_services/initialize.dart';

// 初始化服务
await initializeAppstraxServices(
  apiUrl: 'https://<your-appstrax-services-instance>',
  apiKey: '<your-appstrax-services-instance-api-key>',
);

Auth服务

注册

RegisterDto registerDto = RegisterDto(
  email: 'joe@soap.com',
  password: '<password>',
  data: {
    // 任何额外的自定义用户字段
    'name': 'Joe',
    'surname': 'Soap',
    ...
  }
);

try {
  AuthResult result = await appstraxAuth.register(registerDto);
  User user = result.user!;
  print('用户成功注册,userId: ${user.id}');
} catch (err) {
  // 注册时出错
  handleError(err);
}

登录

LoginDto loginDto = LoginDto(
  email: 'email',
  password: '<password>',
);

try {
  AuthResult result = await appstraxAuth.login(loginDto);
  User user = result.user!;
  print('用户成功登录,userId: ${user.id}');
} catch (err) {
  // 登录时出错
  handleError(err);
}

忘记密码

ForgotPasswordDto forgotPasswordDto = ForgotPasswordDto(
  email: 'email'
);

try {
  Message message = await appstraxAuth.forgotPassword(forgotPasswordDto);
  print('忘记密码邮件已发送: ${message.message}');
} catch (err) {
  // 发送邮件时出错
  handleError(err);
}

发送一封包含密码重置代码的电子邮件给用户,该代码有效期为24小时。

重置密码

ResetPasswordDto resetPasswordDto = ResetPasswordDto(
  email: 'email',
  code: '<code>',
  password: '<password>',
);

try {
  Message message = await appstraxAuth.resetPassword(resetPasswordDto);
  print('密码成功重置: ${message.message}');
} catch (err) {
  // 重置密码时出错
  handleError(err);
}

密码现在已重置,但用户需要使用新密码重新登录。

修改密码

ChangePasswordDto changePasswordDto = ChangePasswordDto(
  password: '<currentPassword>',
  newPassword: '<newPassword>',
);

try {
  User user = await appstraxAuth.changePassword(changePasswordDto);
  print('修改了userId: ${user.id}的密码');
} catch (err) {
  // 修改密码时出错
  handleError(err);
}

用户只能在已认证的情况下修改密码。

更新用户数据/资料

try {
  User updatedUser = await appstraxAuth.saveUserData({
    // 任何额外的自定义用户字段
    'name': 'Joe',
    'surname': 'Soap',
    'career': 'Software Engineer',
    ...
  });
  print('用户数据成功更新,userId: ${updatedUser.id}');
} catch (err) {
  // 更新用户数据时出错
  handleError(err);
}

用户只能在已认证的情况下更新其数据。

登出

try {
  await appstraxAuth.logout();
} catch (err) {
  // 登出时出错
  handleError(err);
}

Auth错误消息

class AuthErrors {
  // 注册错误
  static const emailAddressAlreadyExists = 'emailAddressAlreadyExists';
  static const badlyFormattedEmailAddress = 'badlyFormattedEmailAddress';
  static const noPasswordSupplied = 'noPasswordSupplied';

  // 登录错误
  static const invalidEmailOrPassword = 'invalidEmailOrPassword';
  static const userBlocked = 'userBlocked';
  static const invalidTwoFactorAuthCode = 'invalidTwoFactorAuthCode';

  // 忘记/重置密码错误
  static const emailAddressDoesNotExist = 'emailAddressDoesNotExist';
  static const invalidResetCode = 'invalidResetCode';

  // 未知错误
  static const unexpectedError = 'unexpectedError';
}

用户服务

公共可用性

Admin面板 -> 配置选项卡 -> 公共访问 -> 切换“允许公共访问”

查询用户

FetchQuery query = FetchQuery(
  where: { email: { Operator.LIKE: 'Joe' } },
  order: {},
  offset: 0,
  limit: 5,
);

try {
  FindResult users = await appstraxUsers.find(query: query);
  totalUsers = users.count;
  userData = users.data;
} catch (err) {
  // 查询用户时出错
  handleError(err);
}

示例查询

SELECT * FROM users WHERE email LIKE ‘%Joe%’ ORDER BY email ASC LIMIT 5

FetchQuery query = FetchQuery(
  where: { email: { Operator.LIKE: 'Joe' } },
  order: {},
  offset: 0,
  limit: 5,
);

SELECT * FROM users WHERE email LIKE ‘%Joe%’ OR name LIKE ‘%Joe%’ OR surname LIKE ‘%Joe%’ LIMIT 5

FetchQuery query = FetchQuery(
  where: {
    Operator.OR: [
      { email: { Operator.LIKE: 'Joe' } },
      { name: { Operator.LIKE: 'Joe' } },
      { surname: { Operator.LIKE: 'Joe' } },
    ],
  },
  order: { "email": OrderDirection.ASC },
  offset: 0,
  limit: 5,
);

数据库服务

创建

try {
  var document = await appstraxDb.create('testing', {
    'name': 'John',
    'surname': 'Doe',
    'dogs': 3,
    'career': 'Software Engineer',
  });
  createdId = document.id;
  print('文档创建成功,docId: $createdId');
} catch (err) {
  // 创建时出错
  handleError(err);
}

编辑

try {
  var document = await appstraxDb.edit('testing', createdId, {
    'name': 'John',
    'surname': 'Doe',
    'dogs': 3,
    'career': 'Senior Software Engineer',
    'added': 'this field'
  });
  print('文档编辑成功: ${document.id}');
} catch (err) {
  // 编辑时出错
  handleError(err);
}

删除

try {
  await appstraxDb.delete('testing', createdId as String);
  print('文档删除成功。');
} catch (err) {
  // 删除时出错
  handleError(err);
}

查找ById

try {
  var document = await appstraxDb.findById('testing', createdId as String);
  print('通过Id找到文档: ${document.id}');
} catch (err) {
  // 查询'testing'集合时出错
  handleError(err);
}

查找

try {
  var documents = await appstraxDb.find('testing');
  if (documents.data?.length != null) {
    documents.data?.forEach((user) {
      print('docId: ${user.id}');
    });
  }
} catch (err) {
  // 查询'testing'集合时出错
  handleError(err);
}

CRUD服务

创建自定义模型和服务

// 创建自定义模型
import 'package:json_annotation/json_annotation.dart';
import 'package:appstrax_services/shared/models/model.dart';

part 'person.g.dart';

@JsonSerializable()
class Person implements Model {
  @override
  String? id;
  @override
  DateTime? createdAt;
  @override
  DateTime? updatedAt;
  String name;
  String surname;
  String career;
  int dogs;

  Person({
    this.id,
    this.createdAt,
    this.updatedAt,
    required this.name,
    required this.surname,
    required this.career,
    required this.dogs,
  });

  factory Person.fromJson(Map<String, dynamic> json) => _$PersonFromJson(json);
  @override
  Map<String, dynamic> toJson() => _$PersonToJson(this);
}

// 生成person.g.dart文件
flutter pub run build_runner build

// 创建自定义服务
class PersonService extends CrudService<Person> {
  PersonService() : super('person', Person.fromJson);
}

var personService = PersonService();

使用CRUD服务

try {
  Person person = Person(
    name: 'James',
    surname: 'Doe',
    career: 'farmer',
    dogs: 9,
  );

  // save检查是否有ID,如果存在则编辑,否则创建
  var createdPerson = await personService.save(person);
  personCreatedId = createdPerson.id;
  print('人员创建成功: ${createdPerson.id}');
} catch (err) {
  // 保存时出错
  handleError(err);
}

try {
  var foundPerson = await personService.findById(personCreatedId as String);
  print('通过Id找到人员: ${foundPerson.id}');
} catch (err) {
  // 查询时出错
  handleError(err);
}

try {
  var foundPersons = await personService.find();
  if (foundPersons != null) {
    for (var per in foundPersons) {
      print('DocId: ${per.id}');
    }
  }
} catch (err) {
  // 查询时出错
  handleError(err);
}

try {
  var foundPersons = await personService.find(
    query: FetchQuery(where: {
      'name': {Operator.equal: 'James'}
    }),
  );
  if (foundPersons != null) {
    for (var per in foundPersons) {
      print('DocId: ${per.id}');
    }
  }
} catch (err) {
  // 查询时出错
  handleError(err);
}

存储服务

示例

上传文件

try {
  Response res = await appstraxStorage.uploadFile(file, '<folder>/',
    options: HttpOptions(
      onUploadProgress: (progress) => print(
        '上传进度: ${progress.percent}',
      ),
  ));
  downloadUrl = res.downloadUrl;
  print('下载URL: ${res.downloadUrl}');
} catch (err) {
  // 上传时出错
  handleError(err);
}

删除文件

try {
  await appstraxStorage.deleteFile(downloadUrl as String);
  print('删除成功');
} catch (err) {
  // 删除时出错
  handleError(err);
}

查询模型

FetchQuery

class FetchQuery {
  // 查询条件
  Map<String, dynamic>? where;
  // 排序方向
  Map<String, dynamic>? order;
  // 分页变量
  int? offset;
  int? limit;
}

OrderDirection

class OrderDirection {
  // 升序
  static const asc = 'ASC';
  // 降序
  static const desc = 'DESC';
}

QueryOperators

class Operator {
  // 等于操作符
  static const String equal = 'EQUAL';
  // 不等于操作符
  static const String notEqual = 'NOT_EQUAL';
  // 与操作符
  static const String and = 'AND';
  // 或操作符
  static const String or = 'OR';
  // 大于操作符
  static const String gt = 'GT';
  // 大于等于操作符
  static const String gte = 'GTE';
  // 小于操作符
  static const String lt = 'LT';
  // 小于等于操作符
  static const String lte = 'LTE';
  // 模糊匹配操作符
  static const String like = 'LIKE';
  // 不模糊匹配操作符
  static const String notLike = 'NOT_LIKE';
  // 包含操作符
  static const String qIn = 'IN';
}

查询结果

class FindResultDto<T extends DocumentDto> {
  List<DocumentDto>? data;
  dynamic where;
  dynamic order;
  int? limit;
  int? offset;
  int? count;

  FindResultDto({
    this.data,
    this.where,
    this.order,
    this.limit,
    this.offset,
    this.count,
  });
}

class DocumentDto {
  final String id;
  final Map<String, dynamic> data;
  final DateTime createdAt;
  final DateTime updatedAt;

  DocumentDto(
    this.id,
    this.data,
    this.createdAt,
    this.updatedAt,
  );
}

更多关于Flutter应用追踪与分析插件appstrax_services的使用的实战教程也可以访问 https://www.itying.com/category-92-b0.html

1 回复

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


appstrax_services 是一个用于 Flutter 应用的追踪与分析插件,它可以帮助开发者收集应用的使用数据、用户行为、性能指标等信息,以便更好地优化应用和提升用户体验。以下是如何在 Flutter 应用中使用 appstrax_services 插件的基本步骤:

1. 添加依赖

首先,在 pubspec.yaml 文件中添加 appstrax_services 插件的依赖。打开 pubspec.yaml 文件,在 dependencies 部分添加以下内容:

dependencies:
  flutter:
    sdk: flutter
  appstrax_services: ^1.0.0  # 请使用最新版本

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

2. 初始化插件

在应用的入口文件(通常是 main.dart)中初始化 appstrax_services 插件。你需要在 main 函数中调用 AppstraxServices.initialize() 方法,并传入必要的配置参数。

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

void main() async {
  WidgetsFlutterBinding.ensureInitialized();
  
  // 初始化 AppstraxServices
  await AppstraxServices.initialize(
    apiKey: 'YOUR_API_KEY',  // 替换为你的 API Key
    appId: 'YOUR_APP_ID',    // 替换为你的应用 ID
    appVersion: '1.0.0',     // 替换为你的应用版本号
  );

  runApp(MyApp());
}

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

3. 追踪事件

你可以在应用的不同位置使用 AppstraxServices.trackEvent() 方法来追踪用户行为或应用事件。例如,当用户点击某个按钮时,你可以追踪这个事件:

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

class MyHomePage extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Flutter Demo Home Page'),
      ),
      body: Center(
        child: ElevatedButton(
          onPressed: () {
            // 追踪按钮点击事件
            AppstraxServices.trackEvent(
              eventName: 'button_click',
              properties: {
                'button_name': 'start_button',
              },
            );
          },
          child: Text('Start'),
        ),
      ),
    );
  }
}

4. 追踪用户属性

你可以使用 AppstraxServices.setUserProperty() 方法来设置用户属性,例如用户的性别、年龄等信息:

AppstraxServices.setUserProperty(
  key: 'gender',
  value: 'male',
);

5. 追踪屏幕视图

你可以使用 AppstraxServices.trackScreenView() 方法来追踪用户访问的屏幕视图:

AppstraxServices.trackScreenView(
  screenName: 'home_screen',
);

6. 错误追踪

你还可以使用 AppstraxServices.trackError() 方法来追踪应用中的错误信息:

try {
  // 可能抛出异常的代码
} catch (e, stackTrace) {
  AppstraxServices.trackError(
    error: e,
    stackTrace: stackTrace,
  );
}

7. 调试与日志

在开发过程中,你可以启用调试模式来查看插件的日志输出:

AppstraxServices.setDebugEnabled(true);
回到顶部