Flutter推送通知插件push_notification的使用

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

Flutter推送通知插件push_notification的使用

插件介绍

push_notification 是一个用于实现推送通知的Flutter插件,它属于SurfGear工具包的一部分。该插件包含处理推送通知的主要功能。

安装示例

pubspec.yaml文件中添加以下依赖项:

dependencies:
  push_notification: $currentVersion$

当前版本为:推送到GitHub

示例代码

下面是一个完整的示例代码,展示了如何使用push_notification插件来发送推送通知:

// Copyright (c) 2019-present, SurfStudio LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

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

void main() => runApp(const MyApp());

class MyApp extends StatefulWidget {
  const MyApp({Key? key}) : super(key: key);

  @override
  _MyAppState createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
  late Notificator notification;

  String notificationKey = 'key';
  String _bodyText = 'notification test';

  @override
  void initState() {
    super.initState();
    notification = Notificator(
      onPermissionDecline: () {
        // ignore: avoid_print
        print('permission decline');
      },
      onNotificationTapCallback: (notificationData) {
        setState(() {
          _bodyText = 'notification open: ${notificationData[notificationKey].toString()}';
        });
      },
    )..requestPermissions(
        requestSoundPermission: true,
        requestAlertPermission: true,
      );
  }

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: const Text('Plugin example app'),
        ),
        body: Center(
          child: Text(_bodyText),
        ),
        floatingActionButton: FloatingActionButton(
          onPressed: () {
            notification.show(
              1,
              'hello',
              'this is test',
              imageUrl: 'https://www.lumico.io/wp-019/09/flutter.jpg',
              data: {notificationKey: '[notification data]'},
              notificationSpecifics: NotificationSpecifics(
                AndroidNotificationSpecifics(
                  autoCancelable: true,
                ),
              ),
            );
          },
          child: const Icon(
            Icons.notifications,
            color: Colors.white,
          ),
        ),
      ),
    );
  }
}

使用说明

1 创建通知数据类型:通过继承NotificationPayload类来创建通知数据。 2 创建通知处理策略:通过继承PushHandleStrategy类来创建通知处理策略。 3 创建策略工厂:通过继承PushHandleStrategyFactory类来创建策略工厂。 4 接收通知:需要创建MessagingService实例。 5 显示通知:需要创建NotificationController实例。 6 传递创建的实例:在创建PushHandler时传递这些实例,以便使用工厂创建策略。 7 通知字段:确保通知中有click_action: FLUTTER_NOTIFICATION_CLICK字段。 8 配置Manifest:在<activity>标签中添加intent filter

&lt;intent-filter&gt;
  &lt;action android:name="FLUTTER_NOTIFICATION_CLICK" /&gt;
  &lt;category android:name="android.intent.category.DEFAULT" /&gt;
&lt;/intent-filter&gt;

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

1 回复

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


当然,以下是如何在Flutter项目中使用push_notification插件来实现推送通知的一个基本示例。请注意,push_notification插件的具体名称和用法可能会根据时间变化有所不同,这里我们假设你指的是一个常见的推送通知插件,如flutter_local_notifications,它支持本地和远程通知。

首先,确保在pubspec.yaml文件中添加依赖项:

dependencies:
  flutter:
    sdk: flutter
  flutter_local_notifications: ^9.3.2  # 请根据最新版本调整

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

接下来,在你的Flutter应用中初始化并使用这个插件。以下是一个基本的示例代码:

主文件 main.dart

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

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

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

class NotificationButton extends StatefulWidget {
  @override
  _NotificationButtonState createState() => _NotificationButtonState();
}

class _NotificationButtonState extends State<NotificationButton> {
  final FlutterLocalNotificationsPlugin flutterLocalNotificationsPlugin =
      FlutterLocalNotificationsPlugin();

  var initializationSettingsAndroid;
  var initializationSettingsIOS;
  var initializationSettings;

  @override
  void initState() {
    super.initState();
    var androidInitializationSettings = AndroidInitializationSettings('@mipmap/ic_launcher');
    var iOSInitializationSettings = IOSInitializationSettings(
      requestAlertPermission: true,
      requestBadgePermission: true,
      requestSoundPermission: true,
    );
    initializationSettingsAndroid = AndroidInitializationSettings(
      androidInitializationSettings,
    );
    initializationSettingsIOS = IOSInitializationSettings(iOSInitializationSettings);
    initializationSettings = InitializationSettings(
      android: initializationSettingsAndroid,
      iOS: initializationSettingsIOS,
    );

    flutterLocalNotificationsPlugin.initialize(initializationSettings,
        onSelectNotification: onSelectNotification);
  }

  Future<void> _showNotification() async {
    var androidPlatformChannelSpecifics = AndroidNotificationDetails(
      'your channel id',
      'your channel name',
      'your channel description',
      importance: Importance.max,
      priority: Priority.high,
    );
    var iOSPlatformChannelSpecifics = IOSNotificationDetails();
    var platformChannelSpecifics = NotificationDetails(
      android: androidPlatformChannelSpecifics,
      iOS: iOSPlatformChannelSpecifics,
    );
    await flutterLocalNotificationsPlugin.show(
      0,
      'plain title',
      'plain body',
      platformChannelSpecifics,
      payload: 'item x',
    );
  }

  Future<void> onSelectNotification(String payload) async {
    showDialog(
      context: context,
      builder: (_) {
        return AlertDialog(
          title: Text('Payload'),
          content: Text('Notification payload: $payload'),
        );
      },
    );
  }

  @override
  Widget build(BuildContext context) {
    return ElevatedButton(
      onPressed: _showNotification,
      child: Text('Show Notification'),
    );
  }
}

Android 权限和渠道配置

android/app/src/main/AndroidManifest.xml中,确保你有以下权限:

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

创建或更新android/app/src/main/res/xml/channels.xml来定义通知渠道(如果你的目标SDK版本是26或更高):

<resources xmlns:android="http://schemas.android.com/apk/res/android">
    <channel android:name="your channel id"
             android:importance="high"
             android:sound="default"
             android:vibrationPattern="[0, 500, 1000]"
             android:showBadge="true"
             android:lightSettings="color=#FF0000FF">
        <description>your channel description</description>
    </channel>
</resources>

android/app/src/main/kotlin/.../MainActivity.kt(或Java对应文件)中初始化插件:

import io.flutter.embedding.android.FlutterActivity
import io.flutter.embedding.engine.FlutterEngine
import io.flutter.plugins.flutter_local_notifications.FlutterLocalNotificationsPlugin

class MainActivity: FlutterActivity() {
    override fun configureFlutterEngine(flutterEngine: FlutterEngine) {
        super.configureFlutterEngine(flutterEngine)
        FlutterLocalNotificationsPlugin.registerWith(flutterEngine.dartExecutor.binaryMessenger)
    }
}

iOS 配置

ios/Runner/Info.plist中,添加以下权限请求:

<key>UIBackgroundModes</key>
<array>
    <string>remote-notification</string>
</array>
<key>UIApplicationSupportsMultipleWindows</key>
<true/>

AppDelegate.swiftAppDelegate.m中配置插件(这里以Swift为例):

import UIKit
import Flutter
import flutter_local_notifications

@UIApplicationMain
@objc class AppDelegate: FlutterAppDelegate {
  override func application(
    _ application: UIApplication,
    didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?
  ) -> Bool {
    GeneratedPluginRegistrant.register(with: self)
    let notificationPlugin = FlutterLocalNotificationsPlugin()
    notificationPlugin.register(
      with: registrar(forPlugin: "flutter_local_notifications"),
      options: nil
    )
    return super.application(application, didFinishLaunchingWithOptions: launchOptions)
  }
}

以上代码展示了如何在Flutter应用中集成并使用推送通知插件。请根据你的具体需求调整代码和配置。

回到顶部