Flutter后端服务集成插件kumulos_sdk_flutter的使用
Flutter后端服务集成插件kumulos_sdk_flutter的使用
Kumulos 提供了一系列工具,用于构建和托管应用程序的后端存储、发送推送通知、查看受众和行为分析,以及报告采用率、参与度和性能。
开始使用
在您的 pubspec.yaml
文件中添加以下依赖项,并运行 pub get
:
dependencies:
kumulos_sdk_flutter: 1.2.1
接下来,在项目的根目录下创建一个 kumulos.json
文件,包含 Kumulos 配置:
{
"apiKey": "YOUR_API_KEY",
"secretKey": "YOUR_SECRET_KEY",
"enableCrashReporting": false,
"inAppConsentStrategy": "in-app-disabled",
"enableDeferredDeepLinking": false
}
在您的 pubspec.yaml
文件中声明该资产:
assets:
- kumulos.json
在您的 Dart 代码中,您可以导入并使用 Kumulos 的功能:
import 'package:kumulos_sdk_flutter/kumulos.dart';
var installId = await Kumulos.installId;
如需了解更多关于如何将 Kumulos Flutter SDK 集成到您的项目中的信息,请参阅 Kumulos Flutter 集成指南。
贡献
如果您希望对 Kumulos Flutter SDK 进行改进,欢迎提交拉取请求。如果涉及较大的改动且您不确定是否合适,我们可以先讨论。您可以提交问题或直接联系我们的支持邮箱:support@kumulos.com
。
许可证
该项目基于 MIT 许可证发布,部分代码受 BSD 2-Clause 许可证保护。更多详细信息请查看我们的 LICENSE
文件和源代码文件。
完整示例代码
以下是完整的示例代码,展示如何使用 kumulos_sdk_flutter
插件:
example/lib/main.dart
import 'dart:async';
import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:kumulos_sdk_flutter/kumulos.dart';
void main() {
WidgetsFlutterBinding.ensureInitialized();
runZonedGuarded(() {
FlutterError.onError = Kumulos.onFlutterError;
runApp(MyApp());
}, Kumulos.logUncaughtError);
}
class MyApp extends StatelessWidget {
[@override](/user/override)
Widget build(BuildContext context) {
return MaterialApp(home: HomePage());
}
}
class HomePage extends StatefulWidget {
[@override](/user/override)
State<StatefulWidget> createState() {
return _HomePageState();
}
}
class _HomePageState extends State<HomePage> {
[@override](/user/override)
void initState() {
super.initState();
// 设置事件处理程序
Kumulos.setEventHandlers(
pushReceivedHandler: (push) {
_showAlert('Received Push', [
Text(push.title ?? 'No title'),
Text(push.message ?? 'No message'),
]);
},
pushOpenedHandler: (push) {
_showAlert('Opened Push', [
Text(push.title ?? 'No title'),
Text(push.message ?? 'No message'),
Text(''),
Text('Action button tapped: ${push.actionId ?? 'none'}'),
Text('Data:'),
Text(jsonEncode(push.data)),
]);
},
inAppDeepLinkHandler: (data) {
_showAlert('In-App Message Button Press', [Text(data.toString())]);
},
deepLinkHandler: (outcome) {
var children = [
Text('Url: ${outcome.url}'),
Text('Resolved: ${outcome.resolution}')
];
if (outcome.resolution == KumulosDeepLinkResolution.LinkMatched) {
children.addAll([
Text('Link title: ${outcome.content?.title}'),
Text('Link description: ${outcome.content?.description}'),
Text('Link data:'),
Text(jsonEncode(outcome.linkData)),
]);
}
_showAlert('Kumulos Deep Link', children);
},
);
}
[@override](/user/override)
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text('Plugin example app'),
),
body: SingleChildScrollView(
child: SafeArea(
child: Container(
margin: EdgeInsets.only(left: 20, right: 20, top: 10),
child: Column(
mainAxisSize: MainAxisSize.min,
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
ElevatedButton(
onPressed: () async {
var installId = await Kumulos.installId;
_showAlert('Install ID', [Text(installId)]);
},
child: Text('Install ID'),
),
Text('User Operations'),
ElevatedButton(
onPressed: () async {
var currentUserId = await Kumulos.currentUserIdentifier;
_showAlert('User Identifier', [
Text('''
Currently identified as:
$currentUserId
If no user is currently associated, this will be the install ID.'''),
]);
},
child: Text('Current user identifier'),
),
ElevatedButton(
onPressed: () async {
await Kumulos.associateUserWithInstall(
identifier: 'Robot',
attributes: {'batteryLevel': 96});
var currentUserId = await Kumulos.currentUserIdentifier;
_showAlert('User Identifier', [
Text('''
Changed associated user to:
$currentUserId'''),
]);
},
child: Text('Associate as user "Robot"'),
),
ElevatedButton(
onPressed: () async {
await Kumulos.clearUserAssociation();
var currentUserId = await Kumulos.currentUserIdentifier;
_showAlert('User Identifier', [
Text('''
Changed associated user to:
$currentUserId
(this is the install ID)'''),
]);
},
child: Text('Clear associated user'),
),
Text('Events'),
ElevatedButton(
onPressed: () async {
Kumulos.trackEvent(
eventType: 'product.purchased',
properties: {'productSku': 'example'});
_showAlert('Tracked Event', [
Text(
'The event was tracked locally and queued for batched sending to the server later.'),
]);
},
child: Text('Track "product.purchased" event'),
),
ElevatedButton(
onPressed: () async {
Kumulos.trackEventImmediately(
eventType: 'product.purchased',
properties: {'productSku': 'example'});
_showAlert('Tracked Event', [
Text('The event was tracked and sent to the server.'),
]);
},
child: Text('Track "product.purchased" immediately'),
),
Text('Push'),
ElevatedButton(
onPressed: () async {
Kumulos.pushRequestDeviceToken();
},
child: Text('Request push token'),
),
ElevatedButton(
onPressed: () async {
Kumulos.pushUnregister();
},
child: Text('Unregister from push'),
),
ElevatedButton(
onPressed: () async {
var mgr = await Kumulos.pushChannelManager;
var channels = await mgr.listChannels();
var list = channels
.map((c) => Text('${c.uuid} ${c.name} ${c.isSubscribed ? '(subscibed)' : ''}'))
.toList();
_showAlert('Channels', list);
},
child: Text('List channels'),
),
ElevatedButton(
onPressed: () async {
var mgr = await Kumulos.pushChannelManager;
await mgr.clearSubscriptions();
_showAlert('Channels', [Text('Cleared subscriptions')]);
},
child: Text('Clear subscriptions'),
),
ElevatedButton(
onPressed: () async {
var mgr = await Kumulos.pushChannelManager;
await mgr.setSubscriptions(['dinosaurs', 'ninjas']);
_showAlert('Channels', [Text('Set subscriptions')]);
},
child: Text('Set subscriptions'),
),
ElevatedButton(
onPressed: () async {
var mgr = await Kumulos.pushChannelManager;
await mgr.subscribe(['ninjas']);
_showAlert('Channels', [Text('Subscribed to "ninjas"')]);
},
child: Text('Subscribe "ninjas"'),
),
ElevatedButton(
onPressed: () async {
var mgr = await Kumulos.pushChannelManager;
await mgr.unsubscribe(['dinosaurs']);
_showAlert(
'Channels', [Text('Unsubscribed from "dinosaurs"')]);
},
child: Text('Unsubscribe "dinosaurs"'),
),
ElevatedButton(
onPressed: () async {
var mgr = await Kumulos.pushChannelManager;
var channel = await mgr.createChannel(
uuid: 'vikings',
name: 'Vikings',
showInPortal: true,
subscribe: true,
meta: {'sea_skill': 8});
_showAlert('Channels', [Text('Created ${channel.name}')]);
},
child: Text('Create "vikings"'),
),
Text('In App'),
ElevatedButton(
onPressed: () async {
Navigator.push(context,
MaterialPageRoute(builder: (context) => Inbox()));
},
child: Text('Inbox'),
),
ElevatedButton(
onPressed: () async {
var summary = await KumulosInApp.getInboxSummary();
_showAlert('In-app inbox summary', [
Text('Total: ${summary?.totalCount} Unread: ${summary?.unreadCount}')
]);
},
child: Text('In-app inbox summary'),
),
ElevatedButton(
onPressed: () async {
await KumulosInApp.updateConsentForUser(true);
_showAlert('In-app consent', [Text('Opted in to in-app messaging')]);
},
child: Text('Opt in'),
),
ElevatedButton(
onPressed: () async {
await KumulosInApp.updateConsentForUser(false);
_showAlert('In-app consent', [Text('Opted out from in-app messaging')]);
},
child: Text('Opt out'),
),
Text('Location'),
ElevatedButton(
onPressed: () async {
Kumulos.sendLocationUpdate(latitude: 0, longitude: 0);
_showAlert('Tracked Event', [Text('Sent location update.')]);
},
child: Text('Send location (0,0)'),
),
Text('Crash'),
ElevatedButton(
onPressed: () {
throw "Oops, an unexpected error happened";
},
child: Text('Throw an unexpected error'),
),
ElevatedButton(
onPressed: () {
Kumulos.logError("We knew about this one", StackTrace.current);
},
child: Text('Record expected error'),
),
Text('Backend'),
ElevatedButton(
onPressed: () async {
var client = await Kumulos.backendRpcClient;
// 这是一个示例方法调用,如果未在您的 Kumulos 应用中定义,则不会工作。
//
// 如需进一步了解 Kumulos 后端功能的使用,请参阅文档:
// https://docs.kumulos.com
var result = await client.call(
methodAlias: 'getUserProfile',
params: {'username': 'kumulos'});
_showAlert('Called API Method', [
Text('Response code: ${result.responseCode}'),
Text('Payload:'),
Text(jsonEncode(result.payload)),
]);
},
child: Text('Call an API'),
),
],
),
),
),
),
);
}
void _showAlert(String title, List<Widget> children) {
showDialog(
context: context,
builder: (BuildContext context) {
return AlertDialog(
title: Text(title),
content: SingleChildScrollView(
child: ListBody(
children: children,
),
),
actions: [
TextButton(
child: Text('OK'),
onPressed: () {
Navigator.of(context).pop();
},
),
],
);
});
}
}
class Inbox extends StatefulWidget {
[@override](/user/override)
State<StatefulWidget> createState() {
return _InboxState();
}
}
class _InboxState extends State<Inbox> {
List<KumulosInAppInboxItem> items = [];
KumulosInAppInboxSummary? summary;
Object? error;
[@override](/user/override)
void initState() {
super.initState();
KumulosInApp.setOnInboxUpdatedHandler(() {
_loadState();
});
_loadState();
}
[@override](/user/override)
void dispose() {
super.dispose();
KumulosInApp.setOnInboxUpdatedHandler(null);
}
[@override](/user/override)
Widget build(BuildContext context) {
var content;
if (null != error) {
content = Container(
margin: EdgeInsets.all(8),
child: Center(child: Text(error.toString())));
} else if (null == summary) {
content = Container(
child: Center(child: CircularProgressIndicator(value: null)));
} else {
content = _renderInbox();
}
return Scaffold(
appBar: AppBar(
title: Text('In-app inbox'),
actions: [
IconButton(
tooltip: 'Mark all read',
onPressed: () {
KumulosInApp.markAllInboxItemsAsRead();
},
icon: Icon(Icons.mark_email_read)),
],
),
body: SafeArea(
child: content,
));
}
_loadState() async {
try {
var items = await KumulosInApp.getInboxItems();
var summary = await KumulosInApp.getInboxSummary();
setState(() {
this.items = items;
this.summary = summary;
error = null;
});
} on PlatformException catch (e) {
// Typically this exception would only happen when the in-app strategy
// is set to explicit-by-user and consent management is being done
// manually.
setState(() {
this.error = e.message;
});
}
}
Widget _renderInbox() {
if (items.length == 0) {
return Center(
child: Text('No items'),
);
}
return Column(children: [
Expanded(
child: ListView.separated(
itemBuilder: (ctx, idx) => _renderItem(items[idx]),
separatorBuilder: (ctx, idx) => Divider(),
itemCount: items.length)),
Container(
margin: EdgeInsets.all(8),
child: Text(
'Total: ${summary?.totalCount} Unread: ${summary?.unreadCount}'),
),
]);
}
Widget _renderItem(KumulosInAppInboxItem item) {
return ListTile(
key: Key(item.id.toString()),
title: Text(item.title),
subtitle: Text(item.subtitle),
leading: Icon(
Icons.label_important,
color: item.isRead
? Theme.of(context).disabledColor
: Theme.of(context).indicatorColor,
),
trailing: item.imageUrl != null
? CircleAvatar(
backgroundColor: Colors.grey.shade400,
backgroundImage: NetworkImage(item.imageUrl!),
)
: null,
onTap: () {
KumulosInApp.presentInboxMessage(item);
},
onLongPress: () {
showModalBottomSheet(
context: context,
builder: (context) {
return SafeArea(
child: Wrap(
children: [
ListTile(
leading: Icon(Icons.mark_email_read),
title: Text(
'Mark as read',
),
onTap: () {
KumulosInApp.markAsRead(item);
Navigator.pop(context);
},
),
ListTile(
leading: Icon(Icons.delete),
title: Text(
'Delete from inbox',
),
onTap: () {
KumulosInApp.deleteMessageFromInbox(item);
Navigator.pop(context);
},
)
],
));
});
},
);
}
}
更多关于Flutter后端服务集成插件kumulos_sdk_flutter的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html
更多关于Flutter后端服务集成插件kumulos_sdk_flutter的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html
kumulos_sdk_flutter
是一个用于在 Flutter 应用中集成 Kumulos 后端服务的插件。Kumulos 是一个移动应用后端服务平台,提供了诸如推送通知、应用内消息、分析、用户管理等功能。通过 kumulos_sdk_flutter
,你可以轻松地将这些功能集成到你的 Flutter 应用中。
安装 kumulos_sdk_flutter
首先,你需要在 pubspec.yaml
文件中添加 kumulos_sdk_flutter
依赖:
dependencies:
flutter:
sdk: flutter
kumulos_sdk_flutter: ^4.0.0
然后运行 flutter pub get
来安装依赖。
初始化 Kumulos SDK
在你的 Flutter 应用中,你需要在应用启动时初始化 Kumulos SDK。通常,你可以在 main.dart
文件中进行初始化。
import 'package:flutter/material.dart';
import 'package:kumulos_sdk_flutter/kumulos_sdk_flutter.dart';
void main() async {
WidgetsFlutterBinding.ensureInitialized();
// 初始化 Kumulos SDK
await Kumulos.init(
apiKey: 'YOUR_API_KEY',
secretKey: 'YOUR_SECRET_KEY',
);
runApp(MyApp());
}
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Kumulos Flutter Demo',
home: HomeScreen(),
);
}
}
class HomeScreen extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Kumulos Flutter Demo'),
),
body: Center(
child: Text('Hello, Kumulos!'),
),
);
}
}
使用 Kumulos 功能
1. 推送通知
Kumulos 提供了推送通知功能。你可以通过以下代码来请求推送通知权限并处理通知:
import 'package:kumulos_sdk_flutter/kumulos_sdk_flutter.dart';
// 请求推送通知权限
Kumulos.pushRequestNotificationPermission();
// 监听推送通知
Kumulos.pushOnMessageReceived((notification) {
print('Received notification: ${notification.title}');
});
2. 应用内消息
Kumulos 还支持应用内消息功能。你可以通过以下代码来显示应用内消息:
import 'package:kumulos_sdk_flutter/kumulos_sdk_flutter.dart';
// 显示应用内消息
Kumulos.inAppShowMessage();
3. 用户分析
Kumulos 提供了用户分析功能,你可以通过以下代码来跟踪用户行为:
import 'package:kumulos_sdk_flutter/kumulos_sdk_flutter.dart';
// 跟踪用户事件
Kumulos.analyticsTrackEvent('button_clicked', {'button_id': 'login_button'});
4. 用户管理
Kumulos 还支持用户管理功能,你可以通过以下代码来创建或更新用户:
import 'package:kumulos_sdk_flutter/kumulos_sdk_flutter.dart';
// 创建或更新用户
Kumulos.usersCreateOrUpdate({
'email': 'user@example.com',
'name': 'John Doe',
});
处理后台通知
如果你需要在应用处于后台时处理通知,你可以使用 Kumulos.pushOnNotificationOpened
方法:
import 'package:kumulos_sdk_flutter/kumulos_sdk_flutter.dart';
// 处理后台通知
Kumulos.pushOnNotificationOpened((notification) {
print('Notification opened: ${notification.title}');
});