Flutter插件appmate_flutter的使用指南
appmate_flutter
appmate_flutter是一个用于实现 Appmate 功能的 Flutter 插件项目。它包含平台特定的 Android 和 iOS 实现代码,帮助开发者快速集成 Appmate 的功能到他们的 Flutter 应用中。
开始使用
此项目是一个 Flutter 插件的起点,提供了帮助文档以指导开发者如何开始使用 Appmate。
有关 Appmate 的更多详细信息和教程,请访问 Appmate 官方网站。
示例代码
以下是一个完整的示例代码,展示了如何使用 appmate_flutter插件来实现一些基本功能。
示例代码:main.dart
import 'dart:async';
import 'dart:developer';
import 'package:appmate_flutter/PurchaseClient.dart';
import 'package:appmate_flutter/helpers/BaseResponse.dart';
import 'package:appmate_flutter/helpers/EntitlementResponse.dart';
import 'package:appmate_flutter/helpers/GenericError.dart';
import 'package:appmate_flutter/helpers/ProductsResponse.dart';
import 'package:appmate_flutter/helpers/UserEventType.dart';
import 'package:appmate_flutter/models/Offerwall.dart';
import 'package:appmate_flutter/models/Product.dart';
import 'package:appmate_flutter_example/offerwall_detail.dart';
import 'package:appmate_flutter_example/settings.dart';
import 'package:appmate_flutter_example/user_id_relation.dart';
import 'package:appmate_flutter_example/util.dart';
import 'package:appmate_flutter_example/widgets/ProductRow.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:shared_preferences/shared_preferences.dart';
void main() {
runApp(MaterialApp(
home: ProductList(),
));
}
class ProductList extends StatefulWidget {
const ProductList({Key? key}) : super(key: key);
[@override](/user/override)
_ProductListState createState() => _ProductListState();
}
class _ProductListState extends State<ProductList> {
List<Product> _products = [];
String _environment = "";
[@override](/user/override)
void initState() {
super.initState();
// 设置 API 密钥并初始化用户 ID
PurchaseClient.setApiKey("p3PHN2ANQb2XpAV7A-uvyQ").then((value) {
PurchaseClient.getUserId().then((userId) {
PurchaseClient.setOneSignalId(userId);
PurchaseClient.setAdvertiseId(userId);
PurchaseClient.setAppsFlyerId(userId);
PurchaseClient.setUserAttributes(
{"userName": "example", "Email": "example@example.com"});
});
});
// 启用沙盒模式和调试日志
PurchaseClient.setSandboxActive(true);
PurchaseClient.enableDebugLogs(true);
setEnvironment();
}
[@override](/user/override)
Widget build(BuildContext context) {
return Scaffold(
resizeToAvoidBottomInset: false,
backgroundColor: Colors.grey[200],
appBar: AppBar(
title: Text('AppMate - ' + _environment),
actions: <Widget>[
IconButton(
icon: Icon(
Icons.settings,
color: Colors.white,
),
onPressed: () {
Navigator.push(
context,
MaterialPageRoute(builder: (context) => Settings()),
).then((completion) {
setEnvironment();
});
},
),
IconButton(
icon: Icon(
Icons.supervised_user_circle,
color: Colors.white,
),
onPressed: () {
Navigator.push(
context,
MaterialPageRoute(builder: (context) => UserIdRelation()),
);
},
),
IconButton(
icon: Icon(
Icons.history,
color: Colors.white,
),
onPressed: () {
Navigator.push(
context,
MaterialPageRoute(builder: (context) => PurchaseList()),
);
},
)
],
centerTitle: false,
backgroundColor: Colors.redAccent,
),
body: SingleChildScrollView(child: _buildProducts()),
);
}
// 设置环境变量
void setEnvironment() async {
final prefs = await SharedPreferences.getInstance();
setState(() {
var env = prefs.getString('_environment');
_environment = (env != null && env.length > 0) ? env : "prod";
});
}
// 显示通过产品 ID 获取产品的对话框
void showProductsByIdAlert() {
TextEditingController _productIdField = TextEditingController();
showCupertinoDialog(
context: context,
builder: (BuildContext context) => CupertinoAlertDialog(
title: const Text('Get Product(s) By Id'),
content: Column(children: [
Text(
"Enter Ids, you can seperate them with commas. ie: test_consumable,test_non_consumable"),
CupertinoTextField(controller: _productIdField)
]),
actions: <Widget>[
CupertinoActionSheetAction(
child: const Text('Cancel'),
onPressed: () {
Navigator.pop(context, 'Cancel');
},
),
CupertinoActionSheetAction(
child: const Text('Get'),
onPressed: () {
getProductsWithIdList(_productIdField.text.split(","));
Navigator.pop(context, '0');
},
)
]),
);
}
// 获取指定 Offerwall 的详细信息
void getOfferwalDetail({required String offerwallId}) {
PurchaseClient.getOfferwall(offerwallId).then((value) {
Offerwall? offerwall = value.offerwall;
GenericError? error = value.error;
String errorMsg = '';
if (error != null) {
errorMsg = error.message ?? '';
}
Navigator.push(
context,
MaterialPageRoute(
builder: (context) =>
OfferwallDetail(offerwall: offerwall, errorMsg: errorMsg)),
);
});
}
// 显示通过 Offerwall ID 获取 Offerwall 的对话框
void showOfferwallByIdAlert() {
TextEditingController _offerwallField = TextEditingController();
showCupertinoDialog(
context: context,
builder: (BuildContext context) => CupertinoAlertDialog(
title: const Text('Enter Offerwall Id'),
content: Column(children: [
CupertinoTextField(controller: _offerwallField),
]),
actions: <Widget>[
CupertinoActionSheetAction(
child: const Text('Get'),
onPressed: () {
String? offerwallId = _offerwallField.text;
if (offerwallId.isEmpty) {
ScaffoldMessenger.of(context).showSnackBar(SnackBar(
content: Text("Enter id please"),
));
} else {
getOfferwalDetail(offerwallId: offerwallId);
}
},
),
CupertinoActionSheetAction(
child: const Text('Get Default Offer'),
onPressed: () {
getOfferwalDetail(offerwallId: '');
},
),
CupertinoActionSheetAction(
child: const Text('Cancel'),
onPressed: () {
Navigator.pop(context, 'Cancel');
},
)
]),
);
}
// 检查产品是否已购买
void isProductPurchased() {
TextEditingController _productIdField = TextEditingController();
showCupertinoDialog(
context: context,
builder: (BuildContext context) => CupertinoAlertDialog(
title: const Text('is Product Purchased'),
content: Column(children: [
Text("Enter Product Id, ie: test_consumable"),
CupertinoTextField(controller: _productIdField)
]),
actions: <Widget>[
CupertinoActionSheetAction(
child: const Text('Cancel'),
onPressed: () {
Navigator.pop(context, 'Cancel');
},
),
CupertinoActionSheetAction(
child: const Text('Get'),
onPressed: () async {
BaseResponse response = await PurchaseClient.isProductPurchased(
_productIdField.text);
if (response.error != null) {
Util.showDialog(
context, response.error!.message ?? "Unknown Error");
} else {
Util.showDialog(
context,
response.success
? "Product Purchased"
: "Product Not Purchased");
}
},
)
]),
);
}
// 显示按类型获取产品的对话框
void showProductsWithTypeAlert() {
showCupertinoModalPopup(
context: context,
builder: (BuildContext context) => CupertinoActionSheet(
title: const Text('Get Products With Type'),
message: const Text('Select Product Type'),
actions: <Widget>[
CupertinoActionSheetAction(
child: const Text('Consumable'),
onPressed: () {
getProductsWithType("0");
Navigator.pop(context, '0');
},
),
CupertinoActionSheetAction(
child: const Text('Nonconsumable'),
onPressed: () {
getProductsWithType("1");
Navigator.pop(context, '1');
},
),
CupertinoActionSheetAction(
child: const Text('Subscription'),
onPressed: () {
getProductsWithType("2");
Navigator.pop(context, '2');
},
)
],
cancelButton: CupertinoActionSheetAction(
child: const Text('Cancel'),
isDefaultAction: true,
onPressed: () {
Navigator.pop(context, 'Cancel');
},
)),
);
}
// 获取所有产品
Future<void> getProducts() async {
setState(() {
_products = [];
});
List<Product> products = [];
try {
ProductsResponse response = await PurchaseClient.getProducts();
if (response.error != null) {
Util.showDialog(context, response.error!.message ?? "Unknown Error");
} else {
products = response.products ?? [];
}
} on Exception catch (e) {
print('Unknown exception: $e');
}
if (!mounted) return;
setState(() {
_products = products;
});
}
// 获取用户权限
Future<void> getEntitlements() async {
try {
EntitlementResponse response = await PurchaseClient.getEntitlements();
showCupertinoDialog(
context: context,
builder: (BuildContext context) => CupertinoAlertDialog(
title: const Text('Entitlements'),
content: Column(children: [
Text(response.entitlements.toString()),
]),
actions: <Widget>[
CupertinoActionSheetAction(
child: const Text('Cancel'),
onPressed: () {
Navigator.pop(context, 'Cancel');
},
),
]),
);
} on Exception catch (err) {
log(err.toString());
}
}
// 发送 Appmate 事件
Future<void> sendAppmateEvvent(String productId, UserEventType eventType) async {
try {
BaseResponse response =
await PurchaseClient.setAppmateEvent(productId, eventType);
if (response.error != null) {
Util.showDialog(context, response.error!.message ?? "Unknown Error");
} else {
Util.showDialog(
context, response.success ? "Set Event Success" : "Unknown Error");
}
} on Exception catch (e) {
print('Unknown exception: $e');
}
}
// 显示设置 Appmate 事件的对话框
Future<void> setAppmateEvent() async {
TextEditingController _productIdField = TextEditingController();
showCupertinoDialog(
context: context,
builder: (BuildContext context) => CupertinoAlertDialog(
title: const Text('setAppmateEvent'),
content: Column(children: [
Text("Enter Product Id, ie: test_consumable"),
CupertinoTextField(controller: _productIdField),
Column(
children: [
OutlinedButton(
child: Text('FIRST_LAUNCH'),
onPressed: () async {
sendAppmateEvvent(
_productIdField.text, UserEventType.FIRST_LAUNCH);
}),
OutlinedButton(
child: Text('VIEW'),
onPressed: () async {
sendAppmateEvvent(
_productIdField.text, UserEventType.VIEW);
}),
OutlinedButton(
child: Text('PURCHASE'),
onPressed: () async {
sendAppmateEvvent(
_productIdField.text, UserEventType.PURCHASE);
}),
],
)
]),
actions: <Widget>[
CupertinoActionSheetAction(
child: const Text('Cancel'),
onPressed: () {
Navigator.pop(context, 'Cancel');
},
)
]),
);
}
// 按类型获取产品
Future<void> getProductsWithType(String type) async {
List<Product> products = [];
try {
ProductsResponse response =
await PurchaseClient.getProductsWithType(type);
if (response.error != null) {
Util.showDialog(context, response.error!.message ?? "Unknown Error");
} else {
products = response.products ?? [];
}
} on PlatformException {}
if (!mounted) return;
setState(() {
_products = products;
});
}
// 按 ID 列表获取产品
Future<void> getProductsWithIdList(List<String> ids) async {
List<Product> products = [];
try {
ProductsResponse response =
await PurchaseClient.getProductsWithIdList(ids);
if (response.error != null) {
Util.showDialog(context, response.error!.message ?? "Unknown Error");
} else {
products = response.products ?? [];
}
} on PlatformException {}
if (!mounted) return;
setState(() {
_products = products;
});
}
// 构建产品列表
Widget _buildProducts() {
return Column(
children: [
TextButton(
onPressed: () {
getProducts();
},
child: Text('Get Products'),
),
TextButton(
onPressed: () {
showProductsWithTypeAlert();
},
child: Text('Get Products With Type'),
),
TextButton(
onPressed: () {
showProductsByIdAlert();
},
child: Text('Get Products By Id'),
),
TextButton(
onPressed: () {
isProductPurchased();
},
child: Text('is Product Purchased'),
),
TextButton(
onPressed: () {
getEntitlements();
},
child: Text('Get Entitlements'),
),
TextButton(
onPressed: () {
setAppmateEvent();
},
child: Text('Appmate Event'),
),
TextButton(
onPressed: () {
showOfferwallByIdAlert();
},
child: Text('Get Offerwall'),
),
ListView.builder(
itemCount: _products.length * 2,
padding: const EdgeInsets.all(10),
shrinkWrap: true,
physics: NeverScrollableScrollPhysics(),
itemBuilder: (BuildContext _context, int i) {
if (i.isOdd) {
return Divider();
}
final int index = i ~/ 2;
if (index >= _products.length) {
return Divider();
}
return ProductRow(p: _products[index]);
})
],
);
}
}
更多关于Flutter插件appmate_flutter的使用指南的实战教程也可以访问 https://www.itying.com/category-92-b0.html
更多关于Flutter插件appmate_flutter的使用指南的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html
appmate_flutter
是一个 Flutter 插件,旨在为开发者提供一些未知或实验性的功能,以增强 Flutter 应用的能力。由于这个插件可能不是官方维护的,或者是一个社区贡献的插件,因此在使用之前,建议仔细阅读其文档和源码,确保其功能和稳定性符合你的需求。
1. 安装 appmate_flutter
插件
首先,你需要在 pubspec.yaml
文件中添加 appmate_flutter
插件的依赖:
dependencies:
flutter:
sdk: flutter
appmate_flutter: ^1.0.0 # 请根据实际情况填写版本号
然后运行 flutter pub get
来安装插件。
2. 导入插件
在你的 Dart 文件中导入 appmate_flutter
插件:
import 'package:appmate_flutter/appmate_flutter.dart';
3. 使用 appmate_flutter
的功能
appmate_flutter
可能提供了一些实验性的功能,比如自定义动画、高级手势处理、设备信息获取等。以下是一些可能的使用示例:
3.1 自定义动画
class MyAnimatedWidget extends StatefulWidget {
[@override](/user/override)
_MyAnimatedWidgetState createState() => _MyAnimatedWidgetState();
}
class _MyAnimatedWidgetState extends State<MyAnimatedWidget> with SingleTickerProviderStateMixin {
AnimationController _controller;
Animation<double> _animation;
[@override](/user/override)
void initState() {
super.initState();
_controller = AnimationController(
duration: const Duration(seconds: 2),
vsync: this,
);
_animation = Tween<double>(begin: 0, end: 300).animate(_controller)
..addListener(() {
setState(() {});
});
_controller.forward();
}
[@override](/user/override)
Widget build(BuildContext context) {
return Center(
child: Container(
width: _animation.value,
height: _animation.value,
color: Colors.blue,
),
);
}
[@override](/user/override)
void dispose() {
_controller.dispose();
super.dispose();
}
}
3.2 高级手势处理
class GestureDemo extends StatelessWidget {
[@override](/user/override)
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Gesture Demo'),
),
body: Center(
child: GestureDetector(
onTap: () {
print('Tapped!');
},
onDoubleTap: () {
print('Double Tapped!');
},
onLongPress: () {
print('Long Pressed!');
},
child: Container(
width: 200,
height: 200,
color: Colors.green,
child: Center(
child: Text('Tap Me!'),
),
),
),
),
);
}
}
3.3 设备信息获取
import 'package:appmate_flutter/appmate_flutter.dart';
class DeviceInfoPage extends StatelessWidget {
[@override](/user/override)
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Device Info'),
),
body: FutureBuilder<Map<String, dynamic>>(
future: AppmateFlutter.getDeviceInfo(),
builder: (context, snapshot) {
if (snapshot.connectionState == ConnectionState.waiting) {
return Center(child: CircularProgressIndicator());
} else if (snapshot.hasError) {
return Center(child: Text('Error: ${snapshot.error}'));
} else {
final deviceInfo = snapshot.data;
return ListView(
children: deviceInfo.entries.map((entry) {
return ListTile(
title: Text(entry.key),
subtitle: Text(entry.value.toString()),
);
}).toList(),
);
}
},
),
);
}
}