Flutter营销自动化插件emarsys_sdk的使用
Flutter营销自动化插件emarsys_sdk的使用
介绍
Flutter插件emarsys_sdk
是SAP Emarsys Customer Engagement的官方插件,用于帮助将Emarsys集成到您的Flutter应用程序中。该插件目前支持iOS和Android平台。
Emarsys SDK使您能够以非常简单的方式使用Mobile Engage和Predict功能。通过在应用程序中集成SDK,我们可以帮助您处理凭证、API调用、打开和事件跟踪以及应用程序中的登录和登出操作。
完整示例Demo
以下是一个完整的示例项目,展示了如何使用emarsys_sdk
插件来设置和使用Emarsys功能。
1. 项目结构
lib/
├── main.dart
├── screens/
│ ├── home_screen.dart
│ ├── inbox_messages.dart
│ ├── mobile_engage.dart
│ └── predict.dart
2. main.dart
文件
import 'package:emarsys_sdk/emarsys_sdk.dart';
import 'package:emarsys_sdk_example/screens/home_screen.dart';
import 'package:emarsys_sdk_example/screens/inbox_messages.dart';
import 'package:emarsys_sdk_example/screens/mobile_engage.dart';
import 'package:emarsys_sdk_example/screens/predict.dart';
import 'package:flutter/material.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'dart:convert';
void main() async {
// 确保Flutter绑定已初始化
WidgetsFlutterBinding.ensureInitialized();
// 获取SharedPreferences实例
SharedPreferences prefs = await SharedPreferences.getInstance();
// 配置Emarsys SDK
await Emarsys.setup(EmarsysConfig(
applicationCode: prefs.getString("appcode") ?? 'EMS74-EFB68', // 应用代码
merchantId: "1428C8EE286EC34B", // 商户ID
androidVerboseConsoleLoggingEnabled: true, // 启用Android日志输出
androidSharedPackageNames: ["com.emarsys.sample"], // 共享包名
androidSharedSecret: "secret", // 共享密钥
iOSEnabledConsoleLogLevels: [
ConsoleLogLevels.BASIC,
ConsoleLogLevels.DEBUG,
ConsoleLogLevels.TRACE,
ConsoleLogLevels.INFO,
ConsoleLogLevels.WARN,
ConsoleLogLevels.ERROR,
], // 启用iOS日志级别
));
// 设置联系人(如果已登录)
if (prefs.getString("loggedInUser") != null) {
Emarsys.setContact(await Emarsys.config.contactFieldId() ?? 2575, prefs.getString("loggedInUser") ?? "");
}
// 注册通知通道
Emarsys.push.registerAndroidNotificationChannels([
NotificationChannel(
id: "ems_sample_news",
name: "News",
description: "News and updates go into this channel",
importance: NotificationChannel.IMPORTANCE_HIGH,
),
NotificationChannel(
id: "ems_sample_messages",
name: "Messages",
description: "Important messages go into this channel",
importance: NotificationChannel.IMPORTANCE_HIGH,
),
]);
// 运行应用程序
runApp(MyApp());
}
class MyApp extends StatelessWidget {
[@override](/user/override)
Widget build(BuildContext context) {
// 检查是否为深色模式
bool isDarkTheme = MediaQuery.of(context).platformBrightness == Brightness.dark;
return MaterialApp(
themeMode: isDarkTheme ? ThemeMode.dark : ThemeMode.light,
theme: ThemeData(
primarySwatch: Colors.blue,
brightness: Brightness.light,
scaffoldBackgroundColor: Colors.white,
bottomNavigationBarTheme: const BottomNavigationBarThemeData(
backgroundColor: Colors.white,
selectedItemColor: Colors.blue,
unselectedItemColor: Colors.grey,
),
),
darkTheme: ThemeData(
primarySwatch: Colors.blue,
brightness: Brightness.dark,
scaffoldBackgroundColor: Colors.grey[900],
bottomNavigationBarTheme: const BottomNavigationBarThemeData(
backgroundColor: Colors.black,
selectedItemColor: Colors.blue,
unselectedItemColor: Colors.grey,
),
),
home: const MainScreen(),
);
}
}
class MainScreen extends StatefulWidget {
const MainScreen({super.key});
[@override](/user/override)
_MainScreenState createState() => _MainScreenState();
}
final messengerKey = GlobalKey<ScaffoldMessengerState>();
class _MainScreenState extends State<MainScreen> {
int _currentIndex = 0;
[@override](/user/override)
void initState() {
super.initState();
_initEventStreams(); // 初始化事件流
}
[@override](/user/override)
Widget build(BuildContext context) {
return Scaffold(
key: messengerKey,
appBar: AppBar(
title: const Text('Emarsys SDK Example'),
),
bottomNavigationBar: BottomNavigationBar(
currentIndex: _currentIndex,
onTap: (newIndex) {
setState(() {
_currentIndex = newIndex;
});
},
items: const [
BottomNavigationBarItem(
icon: Icon(Icons.home),
label: "Home",
),
BottomNavigationBarItem(
icon: Icon(Icons.track_changes),
label: "Tracking",
),
BottomNavigationBarItem(
icon: Icon(Icons.message),
label: "Inbox",
),
BottomNavigationBarItem(
icon: Icon(Icons.bug_report),
label: "Predict",
),
],
),
body: _buildBody(_currentIndex),
);
}
Widget _buildBody(int index) {
switch (index) {
case 0:
return const HomeScreen();
case 1:
return const MobileEngageScreen();
case 2:
return const InboxMessages();
case 3:
return const PredictView();
default:
return const HomeScreen();
}
}
void _initEventStreams() {
// 监听推送事件
Emarsys.push.pushEventStream.listen((event) {
messengerKey.currentState?.showSnackBar(SnackBar(content: Text("${event.name} - ${event.payload}")));
debugPrint(event.name);
});
// 监听静默推送事件
Emarsys.push.silentPushEventStream.listen((event) {
messengerKey.currentState?.showSnackBar(SnackBar(content: Text("${event.name} - ${event.payload}")));
debugPrint(event.name);
});
// 监听地理围栏事件
Emarsys.geofence.geofenceEventStream.listen((event) {
messengerKey.currentState?.showSnackBar(SnackBar(content: Text("${event.name} - ${event.payload}")));
debugPrint(event.name);
});
// 监听应用内消息事件
Emarsys.inApp.inAppEventStream.listen((event) {
messengerKey.currentState?.showSnackBar(SnackBar(content: Text("${event.name} - ${event.payload}")));
debugPrint(event.name);
});
}
}
Map<String, String>? convertTextToMap(String? text) {
Map<String, String>? result;
if (text != null && text.isNotEmpty) {
result = json.decode(text);
}
return result;
}
3. home_screen.dart
文件
import 'package:flutter/material.dart';
class HomeScreen extends StatelessWidget {
const HomeScreen({super.key});
[@override](/user/override)
Widget build(BuildContext context) {
return Center(
child: Text("Welcome to the Home Screen"),
);
}
}
4. inbox_messages.dart
文件
import 'package:flutter/material.dart';
class InboxMessages extends StatelessWidget {
const InboxMessages({super.key});
[@override](/user/override)
Widget build(BuildContext context) {
return Center(
child: Text("Inbox Messages Screen"),
);
}
}
5. mobile_engage.dart
文件
import 'package:flutter/material.dart';
class MobileEngageScreen extends StatelessWidget {
const MobileEngageScreen({super.key});
[@override](/user/override)
Widget build(BuildContext context) {
return Center(
child: Text("Mobile Engage Screen"),
);
}
}
6. predict.dart
文件
import 'package:flutter/material.dart';
class PredictView extends StatelessWidget {
const PredictView({super.key});
[@override](/user/override)
Widget build(BuildContext context) {
return Center(
child: Text("Predict Screen"),
);
}
}
更多关于Flutter营销自动化插件emarsys_sdk的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html
更多关于Flutter营销自动化插件emarsys_sdk的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html
当然,以下是一个关于如何在Flutter项目中集成和使用emarsys_sdk
插件的示例代码案例。请注意,实际使用时,你可能需要根据emarsys_sdk
的最新版本和API文档进行调整。
首先,确保你已经在pubspec.yaml
文件中添加了emarsys_sdk
依赖:
dependencies:
flutter:
sdk: flutter
emarsys_sdk: ^latest_version # 替换为实际最新版本号
然后,运行flutter pub get
来安装依赖。
接下来,在你的Flutter项目中,你可以按照以下步骤初始化并使用emarsys_sdk
:
- 初始化Emarsys SDK:
在你的应用的主入口文件(通常是main.dart
)中,初始化Emarsys SDK。通常,这需要在应用启动时尽早完成。
import 'package:flutter/material.dart';
import 'package:emarsys_sdk/emarsys_sdk.dart';
void main() async {
WidgetsFlutterBinding.ensureInitialized();
// 初始化Emarsys SDK
await EmarsysSdk.init(
apiKey: 'YOUR_API_KEY', // 替换为你的Emarsys API密钥
endpoint: 'YOUR_ENDPOINT', // 替换为你的Emarsys服务端点
);
runApp(MyApp());
}
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: MyHomePage(),
);
}
}
- 注册用户:
在用户注册或登录时,你可以将用户信息发送到Emarsys。
class MyHomePage extends StatefulWidget {
@override
_MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
void registerUser(String email, String firstName, String lastName) async {
try {
await EmarsysSdk.registerUser(
email: email,
firstName: firstName,
lastName: lastName,
);
print('User registered successfully.');
} catch (e) {
print('Error registering user: $e');
}
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Emarsys SDK Demo'),
),
body: Center(
child: ElevatedButton(
onPressed: () {
// 示例用户数据
String email = 'testuser@example.com';
String firstName = 'John';
String lastName = 'Doe';
// 注册用户
registerUser(email, firstName, lastName);
},
child: Text('Register User'),
),
),
);
}
}
- 发送事件:
在用户与应用交互时,你可以发送事件到Emarsys。
void sendEvent(String eventName, Map<String, dynamic> properties) async {
try {
await EmarsysSdk.sendEvent(
eventName: eventName,
properties: properties,
);
print('Event sent successfully.');
} catch (e) {
print('Error sending event: $e');
}
}
// 示例:在某个按钮点击事件中发送事件
ElevatedButton(
onPressed: () {
String eventName = 'product_view';
Map<String, dynamic> properties = {
'product_id': '12345',
'product_name': 'Sample Product',
'category': 'Electronics',
};
// 发送事件
sendEvent(eventName, properties);
},
child: Text('Send Event'),
)
- 跟踪页面视图:
你也可以跟踪用户在应用中的页面视图。
void trackPageView(String pageName, Map<String, dynamic> properties) async {
try {
await EmarsysSdk.trackPageView(
pageName: pageName,
properties: properties,
);
print('Page view tracked successfully.');
} catch (e) {
print('Error tracking page view: $e');
}
}
// 示例:在某个页面加载时跟踪视图
@override
void initState() {
super.initState();
trackPageView('home_page', {});
}
请注意,以上代码是简化的示例,实际使用中你可能需要处理更多的错误情况,并根据你的应用需求调整数据结构和逻辑。务必参考emarsys_sdk
的官方文档以获取最新的API信息和最佳实践。