Flutter推送通知插件pushe_flutter的使用

发布于 1周前 作者 songsunli 来自 Flutter

Flutter推送通知插件pushe_flutter的使用

Pushe 推送通知服务官方插件适用于 Flutter。Pushe 是一个推送通知服务。更多信息可以访问 Pushe 主页

它支持 AndroidiOS(也可以在 Flutter Web 上使用)。

安装

将插件添加到 pubspec.yaml 文件中:

dependencies:
  pushe_flutter: <version>

如果你想要使用最新的版本(不一定已发布且稳定),可以直接使用 GitHub 上的源代码:

pushe_flutter:
  git:
    url: https://github.com/pusheco/pushe-flutter.git

更多关于使用方法和 API 参考的信息可以访问 文档

更多信息

示例代码

以下是完整的示例代码,展示如何在 Flutter 应用中使用 pushe_flutter 插件。

示例代码

example/lib/main.dart

// 导入必要的包
import 'pushe_sample.dart'; // 自定义的pushe相关代码
import 'package:flutter/material.dart'; // Flutter框架核心包

// 应用入口函数
void main() => runApp(PusheSampleApp()); // 运行应用

// 自定义的应用类
class PusheSampleApp extends StatelessWidget { // 继承StatelessWidget
  // 构建应用的方法
  [@override](/user/override)
  Widget build(BuildContext context) {
    return MaterialApp( // 使用MaterialApp构建UI
      title: 'Pushe Flutter', // 设置应用标题
      theme: ThemeData( // 设置主题
        primarySwatch: Colors.indigo, // 设置主要颜色
      ),
      home: PusheSampleWidget() // 设置主页
    );
  }
}

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

1 回复

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


当然,以下是如何在Flutter项目中使用pushe_flutter插件来实现推送通知的一个基本示例。这个插件允许你集成Push.e的推送通知服务。

1. 添加依赖

首先,你需要在pubspec.yaml文件中添加pushe_flutter的依赖:

dependencies:
  flutter:
    sdk: flutter
  pushe_flutter: ^x.y.z  # 请替换为最新版本号

然后运行flutter pub get来安装依赖。

2. 配置Android

2.1 在android/app/src/main/AndroidManifest.xml中添加必要的权限:

<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED"/>
<uses-permission android:name="android.permission.VIBRATE"/>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
<uses-permission android:name="android.permission.WAKE_LOCK"/>

2.2 在android/app/src/main/AndroidManifest.xml中添加服务声明:

<service
    android:name="io.flutter.plugins.pusheflutter.PusheFlutterService"
    android:exported="true">
    <intent-filter>
        <action android:name="com.google.firebase.MESSAGING_EVENT" />
    </intent-filter>
</service>
<receiver android:name="io.flutter.plugins.pusheflutter.PusheBroadcastReceiver" android:exported="true">
    <intent-filter>
        <action android:name="com.pushe.ACTION_MESSAGE_RECEIVED" />
    </intent-filter>
</receiver>

3. 配置iOS

3.1 在ios/Runner/Info.plist中添加必要的权限:

<key>NSAppTransportSecurity</key>
<dict>
    <key>NSAllowsArbitraryLoads</key>
    <true/>
</dict>
<key>UIBackgroundModes</key>
<array>
    <string>remote-notification</string>
</array>
<key>UIApplicationSupportsIndirectInputEvents</key>
<true/>

3.2 在ios/Runner/AppDelegate.swift中配置推送通知:

import UIKit
import Flutter
import pushe_flutter

@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()
        }
      }
    }
    
    application.registerForRemoteNotifications()
    
    return super.application(application, didFinishLaunchingWithOptions: launchOptions)
  }
  
  override func application(_ application: UIApplication,
                            didReceiveRemoteNotification userInfo: [AnyHashable : Any],
                            fetchCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void) {
    PusheFlutterPlugin.sharedInstance().didReceiveRemoteNotification(userInfo, fetchCompletionHandler: completionHandler)
  }
  
  override func application(_ application: UIApplication, didFailToRegisterForRemoteNotificationsWithError error: Error) {
    print("Failed to register for remote notifications: \(error.localizedDescription)")
  }
}

4. 初始化Push.e并处理推送通知

在你的Flutter代码中,初始化pushe_flutter插件并处理推送通知。例如,在main.dart中:

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

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

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

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

class _MyHomePageState extends State<MyHomePage> {
  @override
  void initState() {
    super.initState();
    
    // 初始化Push.e
    PusheFlutter.initialize(
      appId: "YOUR_APP_ID", // 替换为你的Push.e App ID
      appKey: "YOUR_APP_KEY", // 替换为你的Push.e App Key
    );
    
    // 设置推送通知的监听
    PusheFlutter.onMessageReceived.listen((message) {
      print("Received message: ${message.toMap()}");
      // 在这里处理接收到的推送通知
      showDialog(
        context: context,
        builder: (BuildContext context) {
          return AlertDialog(
            title: Text("Push Notification"),
            content: Text(message.toMap()["title"].toString()),
            actions: <Widget>[
              FlatButton(
                child: Text("OK"),
                onPressed: () {
                  Navigator.of(context).pop();
                },
              ),
            ],
          );
        },
      );
    });
  }

  @override
  Widget build(BuildContext context) {
    return Text("Check your console for push notifications.");
  }
}

请确保将YOUR_APP_IDYOUR_APP_KEY替换为你从Push.e获取的实际值。

这个示例展示了如何初始化pushe_flutter插件并处理推送通知。根据实际需求,你可能需要进一步自定义通知的处理逻辑。

回到顶部