Flutter消息推送插件catapush_flutter_sdk的使用
Flutter消息推送插件catapush_flutter_sdk的使用
Catapush 是一个简单、可靠且可扩展的交付API,用于网站和应用程序的事务性推送通知。适用于发送包括目标电子商务和个人化一对一消息在内的数据驱动型事务性通知。
通过实时状态确认每条消息的发送,并在您的应用中构建智能消息逻辑。
安装
请参阅 安装指南 获取安装说明。
示例项目
示例项目位于此存储库的 /example
文件夹中。
示例代码
以下是完整的示例代码,展示了如何使用 catapush_flutter_sdk
插件:
import 'dart:async';
import 'package:catapush_flutter_sdk/catapush_flutter_sdk.dart';
import 'package:catapush_flutter_sdk_example/blocs/authentication/authentication_bloc.dart';
import 'package:catapush_flutter_sdk_example/blocs/catapushMessages/catapush_messages_bloc.dart';
import 'package:catapush_flutter_sdk_example/blocs/catapushState/catapush_state_bloc.dart';
import 'package:catapush_flutter_sdk_example/repositories/authentication_repository.dart';
import 'package:catapush_flutter_sdk_example/repositories/user_repository.dart';
import 'package:catapush_flutter_sdk_example/screens/home.dart';
import 'package:catapush_flutter_sdk_example/screens/login.dart';
import 'package:catapush_flutter_sdk_example/screens/splash.dart';
import 'package:catapush_flutter_sdk_example/theme.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
void main() {
WidgetsFlutterBinding.ensureInitialized();
final userRepository = UserRepository();
runApp(App(
authenticationRepository: AuthenticationRepository(userRepository),
userRepository: userRepository,
));
}
class CMDelegate extends CatapushMessageDelegate {
final CatapushMessagesBloc catapushMessagesBloc;
CMDelegate(this.catapushMessagesBloc);
[@override](/user/override)
void catapushMessageReceived(CatapushMessage message) {
debugPrint('RECEIVED ${message.id}');
catapushMessagesBloc.add(CatapushMessagesEventFetch());
}
[@override](/user/override)
void catapushMessageSent(CatapushMessage message) {
debugPrint('SENT ${message.id}');
catapushMessagesBloc.add(CatapushMessagesEventFetch());
}
[@override](/user/override)
void catapushNotificationTapped(CatapushMessage message) {
debugPrint('NOTIFICATION TAPPED ${message.id}');
}
}
class CSDelegate extends CatapushStateDelegate {
final CatapushStateBloc catapushStateBloc;
CSDelegate(this.catapushStateBloc);
[@override](/user/override)
void catapushHandleError(CatapushError error) {
debugPrint(error.toString());
}
[@override](/user/override)
void catapushStateChanged(CatapushState state) {
catapushStateBloc.add(CatapushStateEvent(state));
}
}
class App extends StatefulWidget {
const App({
super.key,
required this.authenticationRepository,
required this.userRepository,
});
final AuthenticationRepository authenticationRepository;
final UserRepository userRepository;
[@override](/user/override)
AppState createState() => AppState();
}
class AppState extends State<App> {
[@override](/user/override)
Widget build(BuildContext context) {
return RepositoryProvider.value(
value: widget.authenticationRepository,
child: MultiBlocProvider(
providers: [
BlocProvider(
create: (_) => CatapushStateBloc(),
),
BlocProvider(
create: (_) => CatapushMessagesBloc(),
),
BlocProvider(
create: (_) => AuthenticationBloc(
authenticationRepository: widget.authenticationRepository,
userRepository: widget.userRepository,
),
)
],
child: const AppView(),
),
);
}
}
class AppView extends StatefulWidget {
const AppView({super.key});
[@override](/user/override)
AppViewState createState() => AppViewState();
}
class AppViewState extends State<AppView> {
final _navigatorKey = GlobalKey<NavigatorState>();
NavigatorState get _navigator => _navigatorKey.currentState!;
[@override](/user/override)
void initState() {
super.initState();
initCatapush();
}
// 平台消息异步处理,因此我们初始化在异步方法中。
Future<void> initCatapush() async {
Catapush.shared.enableLog(!kReleaseMode);
Catapush.shared.setCatapushMessageDelegate(
CMDelegate(BlocProvider.of<CatapushMessagesBloc>(context)));
Catapush.shared.setCatapushStateDelegate(
CSDelegate(BlocProvider.of<CatapushStateBloc>(context)));
final init = await Catapush.shared.init(
ios: iOSSettings('YOUR_CATAPUSH_APP_KEY'),
);
debugPrint('Init: $init');
}
[@override](/user/override)
Widget build(BuildContext context) {
return MaterialApp(
navigatorKey: _navigatorKey,
themeMode: ThemeMode.system,
theme: lightThemeData,
darkTheme: darkThemeData,
onGenerateRoute: (_) => SplashScreen.route(),
builder: (context, child) {
return BlocListener<AuthenticationBloc, AuthenticationState>(
listener: (context, state) {
switch (state.status) {
case AuthenticationStatus.authenticated:
BlocProvider.of<CatapushMessagesBloc>(context).add(CatapushMessagesEventFetch());
Catapush.shared.setUser(state.user.identifier, state.user.password);
Catapush.shared.start();
_navigator.pushAndRemoveUntil<void>(
HomeScreen.route(),
(route) => false,
);
break;
case AuthenticationStatus.unauthenticated:
_navigator.pushAndRemoveUntil<void>(
LoginScreen.route(),
(route) => false,
);
break;
default:
break;
}
},
child: child,
);
},
);
}
}
更多关于Flutter消息推送插件catapush_flutter_sdk的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html
更多关于Flutter消息推送插件catapush_flutter_sdk的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html
当然,下面是一个关于如何在Flutter项目中使用catapush_flutter_sdk
插件来实现消息推送的示例代码。这个示例假定你已经创建了一个Flutter项目,并且已经在pubspec.yaml
文件中添加了catapush_flutter_sdk
依赖。
1. 添加依赖
首先,在你的pubspec.yaml
文件中添加catapush_flutter_sdk
依赖:
dependencies:
flutter:
sdk: flutter
catapush_flutter_sdk: ^最新版本号 # 请替换为实际的最新版本号
然后运行flutter pub get
来安装依赖。
2. 初始化Catapush SDK
在你的Flutter应用的入口文件(通常是main.dart
)中,初始化Catapush SDK。
import 'package:flutter/material.dart';
import 'package:catapush_flutter_sdk/catapush_flutter_sdk.dart';
void main() {
runApp(MyApp());
// 初始化Catapush SDK
CatapushFlutterSdk.instance.initialize(
appId: "你的Catapush应用ID", // 替换为你的Catapush应用ID
appSecret: "你的Catapush应用密钥", // 替换为你的Catapush应用密钥
onRegistered: (deviceId) {
print("Device registered with ID: $deviceId");
},
onMessageReceived: (message) {
print("Message received: $message");
},
onError: (error) {
print("Error: $error");
}
);
}
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Catapush Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: MyHomePage(),
);
}
}
class MyHomePage extends StatefulWidget {
@override
_MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Flutter Catapush Demo'),
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Text(
'Check console for device registration and message reception.',
),
],
),
),
);
}
}
3. 处理后台消息(可选)
如果你的应用需要在后台接收消息,你需要在AppDelegate.swift
(iOS)和MainActivity.kt
或MainActivity.java
(Android)中进行额外的配置。
iOS (AppDelegate.swift)
确保在AppDelegate.swift
中配置Catapush后台消息处理:
import UIKit
import Flutter
import catapush_flutter_sdk
@UIApplicationMain
@objc class AppDelegate: FlutterAppDelegate {
override func application(
_ application: UIApplication,
didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?
) -> Bool {
GeneratedPluginRegistrant.register(with: self)
CatapushFlutterPlugin.setup(with: application, options: launchOptions)
return super.application(application, didFinishLaunchingWithOptions: launchOptions)
}
// 处理后台消息
override func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable : Any], fetchCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void) {
CatapushFlutterPlugin.didReceiveRemoteNotification(userInfo, fetchCompletionHandler: completionHandler)
}
}
Android (MainActivity.kt 或 MainActivity.java)
在MainActivity.kt
或MainActivity.java
中配置Catapush:
MainActivity.kt:
package com.example.yourapp
import android.os.Bundle
import io.flutter.embedding.android.FlutterActivity
import io.flutter.embedding.engine.FlutterEngine
import io.flutter.plugins.GeneratedPluginRegistrant
import catapush_flutter_sdk.CatapushFlutterPlugin
class MainActivity: FlutterActivity() {
override fun configureFlutterEngine(flutterEngine: FlutterEngine) {
super.configureFlutterEngine(flutterEngine)
GeneratedPluginRegistrant.registerWith(flutterEngine)
CatapushFlutterPlugin.registerWith(flutterEngine.dartExecutor.binaryMessenger)
}
}
MainActivity.java:
package com.example.yourapp;
import android.os.Bundle;
import io.flutter.embedding.android.FlutterActivity;
import io.flutter.embedding.engine.FlutterEngine;
import io.flutter.plugins.GeneratedPluginRegistrant;
import catapush_flutter_sdk.CatapushFlutterPlugin;
public class MainActivity extends FlutterActivity {
@Override
public void configureFlutterEngine(FlutterEngine flutterEngine) {
super.configureFlutterEngine(flutterEngine);
GeneratedPluginRegistrant.registerWith(flutterEngine);
CatapushFlutterPlugin.registerWith(flutterEngine.getDartExecutor().getBinaryMessenger());
}
}
4. 运行应用
现在,你可以运行你的Flutter应用,并检查控制台输出以确认设备注册和消息接收。
注意事项
- 请确保你已经在Catapush后台为你的应用配置了正确的推送证书和密钥。
- 根据你的应用需求,你可能需要处理更多类型的推送消息,比如静默推送、富媒体推送等,这些都可以在Catapush的官方文档中找到详细的配置和使用说明。
这个示例提供了一个基本的框架,帮助你开始在Flutter项目中使用catapush_flutter_sdk
进行消息推送。根据你的具体需求,你可能需要调整和扩展这个示例代码。