Flutter消息推送插件push_express_lib的使用

Flutter消息推送插件push_express_lib的使用

本指南将指导你如何在应用程序中集成PushExpressLib,并处理应用处于前台和后台状态时的消息推送。

开始

首先,在你的main.dart文件中导入该包:

import 'package:push_express_lib/push_express_lib.dart';

然后,你可以在代码中使用该包的功能。

指导

第一步

初始化包

void initFirebase() async {
    // 初始化Firebase应用
    await Firebase.initializeApp(
        options: DefaultFirebaseOptions.currentPlatform,
    );

    // 请求推送通知权限
    await FirebaseMessaging.instance.requestPermission();

    // 获取唯一的FCM令牌
    String? token = await FirebaseMessaging.instance.getToken();

    if (token != null) {
        // 初始化包
        PushExpressManager().init(
            // 从https://app.push.express/获取你的应用ID
            '21486-1212',
            TransportType.fcmData,
            transportToken: token,
            // 如果需要在应用处于前台时接收通知(仅限iOS),设置foreground为true
            foreground: true,
        );
    }
}

[@override](/user/override)
void initState() {
    super.initState();

    // 调用初始化函数
    initFirebase();
}

第二步

启用后台消息处理

Future<void> firebaseMessagingBackgroundHandler(RemoteMessage message) async {
  // 初始化Firebase应用
  await Firebase.initializeApp(
    options: DefaultFirebaseOptions.currentPlatform,
  );

  // 调用包中的函数来处理通知,并在后台正确显示它们
  NotificationManager().handleNotification(message);
}

void main() {
  // 确保小部件已初始化
  WidgetsFlutterBinding.ensureInitialized();

  // 处理Firebase后台消息
  // 并调用我们的处理器
  FirebaseMessaging.onBackgroundMessage(firebaseMessagingBackgroundHandler);

  runApp(const MyApp());
}

第三步(可选)

处理前台消息

// 如果你想在应用处于前台时接收任何推送通知
// 在你的代码中添加以下行
FirebaseMessaging.onMessage.listen(
    // 提供此函数以正确处理通知并显示它们
    NotificationManager().handleNotification,
);

示例

以下是帮助你开始的一些示例代码:

import 'package:firebase_core/firebase_core.dart';
import 'package:firebase_messaging/firebase_messaging.dart';
import 'package:flutter/material.dart';
import 'package:flutter_test_package/firebase_options.dart';
import 'package:push_express_lib/enums/common.dart';
import 'package:push_express_lib/notification_manager.dart';
import 'package:push_express_lib/push_express_lib.dart';

Future<void> firebaseMessagingBackgroundHandler(RemoteMessage message) async {
  await Firebase.initializeApp(
    options: DefaultFirebaseOptions.currentPlatform,
  );
  NotificationManager().handleNotification(message);
}

void main() {
  WidgetsFlutterBinding.ensureInitialized();
  FirebaseMessaging.onBackgroundMessage(firebaseMessagingBackgroundHandler);
  runApp(const MyApp());
}

class MyApp extends StatefulWidget {
  const MyApp({super.key});

  [@override](/user/override)
  State<MyApp> createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
  [@override](/user/override)
  void initState() {
    super.initState();
    initFirebase();
  }

  void initFirebase() async {
    await Firebase.initializeApp(
      options: DefaultFirebaseOptions.currentPlatform,
    );

    await FirebaseMessaging.instance.requestPermission();

    String? token = await FirebaseMessaging.instance.getToken();

    if (token != null) {
      PushExpressManager().init(
        '21486-1212',
        TransportType.fcm,
        transportToken: token,
        foreground: true,
      );
    }

    FirebaseMessaging.onMessage.listen(
      NotificationManager().handleNotification,
    );
  }

  [@override](/user/override)
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        colorScheme: ColorScheme.fromSeed(seedColor: Colors.deepPurple),
        useMaterial3: true,
      ),
      home: const MyHomePage(title: 'Flutter Demo Home Page'),
    );
  }
}

class MyHomePage extends StatefulWidget {
  const MyHomePage({super.key, required this.title});

  final String title;

  [@override](/user/override)
  State<MyHomePage> createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  int _counter = 0;

  void _incrementCounter() {
    setState(() {
      _counter++;
    });
  }

  [@override](/user/override)
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        backgroundColor: Theme.of(context).colorScheme.inversePrimary,
        title: Text(widget.title),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            const Text(
              '你已经点击了按钮这么多次:',
            ),
            Text(
              '$_counter',
              style: Theme.of(context).textTheme.headlineMedium,
            ),
          ],
        ),
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: _incrementCounter,
        tooltip: '增加',
        child: const Icon(Icons.add),
      ),
    );
  }
}

更多关于Flutter消息推送插件push_express_lib的使用的实战教程也可以访问 https://www.itying.com/category-92-b0.html

1 回复

更多关于Flutter消息推送插件push_express_lib的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html


当然,以下是一个关于如何使用Flutter消息推送插件push_express_lib的示例代码。请注意,实际使用中可能需要根据具体的推送服务(如Firebase Cloud Messaging、个推等)进行一些配置和调整。以下示例假设你已经完成了Flutter环境的搭建和基本的Flutter项目创建。

1. 添加依赖

首先,在你的pubspec.yaml文件中添加push_express_lib依赖。由于push_express_lib可能是一个假设的插件名称,实际使用时请替换为真实存在的推送插件名称。这里我们假设插件名为push_express_lib

dependencies:
  flutter:
    sdk: flutter
  push_express_lib: ^x.y.z  # 替换为实际版本号

运行flutter pub get来安装依赖。

2. 配置Android和iOS推送权限

Android

android/app/src/main/AndroidManifest.xml中添加必要的权限和服务声明:

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.yourapp">

    <uses-permission android:name="android.permission.INTERNET"/>
    <uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED"/>
    <uses-permission android:name="android.permission.WAKE_LOCK"/>
    <uses-permission android:name="com.google.android.c2dm.permission.RECEIVE"/>

    <application
        ...>
        
        <!-- 推送服务接收器 -->
        <receiver android:name="com.example.push.MyPushReceiver"
            android:exported="true">
            <intent-filter>
                <action android:name="com.example.yourapp.PUSH_RECEIVER"/>
            </intent-filter>
        </receiver>

        <!-- 其他必要的配置 -->
        
    </application>
</manifest>

iOS

ios/Runner/Info.plist中添加推送通知权限请求:

<key>UIBackgroundModes</key>
<array>
    <string>remote-notification</string>
</array>
<key>UIApplicationSupportsMultipleScenes</key>
<false/>
<key>NSAppTransportSecurity</key>
<dict>
    <key>NSAllowsArbitraryLoads</key>
    <true/>
</dict>
<key>UNNotificationBreakthroughPriority</key>
<integer>1</integer>

AppDelegate.swift中配置推送接收处理:

import UIKit
import Flutter
import UserNotifications

@UIApplicationMain
@objc class AppDelegate: FlutterAppDelegate {
    override func application(
        _ application: UIApplication,
        didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?
    ) -> Bool {
        GeneratedPluginRegistrant.register(with: self)
        
        // 注册推送通知
        UNUserNotificationCenter.current().requestAuthorization(options: [.alert, .sound, .badge]) { (granted, error) in
            if granted {
                DispatchQueue.main.async {
                    application.registerForRemoteNotifications()
                }
            }
        }
        
        return super.application(application, didFinishLaunchingWithOptions: launchOptions)
    }
    
    override func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable : Any], fetchCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void) {
        // 处理推送通知
        if let message = userInfo["aps"]?["alert"] as? String {
            print("Received remote notification: \(message)")
        }
        completionHandler(.newData)
    }
}

3. 初始化并使用推送插件

在你的Flutter项目中,初始化并使用push_express_lib插件:

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

void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: Text('Push Notification Demo'),
        ),
        body: Center(
          child: MyHomePage(),
        ),
      ),
    );
  }
}

class MyHomePage extends StatefulWidget {
  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  @override
  void initState() {
    super.initState();
    
    // 初始化推送插件
    PushExpressLib.instance.initialize().then((result) {
      if (result) {
        print("Push notification initialized successfully.");

        // 注册设备以接收推送通知
        PushExpressLib.instance.registerDevice().then((deviceId) {
          print("Device registered with ID: $deviceId");
        }).catchError((error) {
          print("Error registering device: $error");
        });
      } else {
        print("Failed to initialize push notification.");
      }
    }).catchError((error) {
      print("Error initializing push notification: $error");
    });
  }

  @override
  Widget build(BuildContext context) {
    return Text('Check console for push notification initialization status.');
  }
}

注意

  • 上述代码是一个简化的示例,用于展示如何初始化和使用推送插件。
  • 实际项目中,你需要根据具体的推送服务提供商(如Firebase、个推等)进行详细的配置和代码调整。
  • 确保你的推送服务配置正确,包括API密钥、证书等敏感信息。
  • 测试推送通知时,请使用真实的设备而非模拟器,因为模拟器可能不支持推送通知功能。

希望这个示例能帮助你开始使用Flutter中的消息推送插件。如果有更多具体需求或问题,请随时提问。

回到顶部