Flutter通知管理插件flutter_notification_manager的使用

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

Flutter通知管理插件flutter_notification_manager的使用

1. 创建通知通道

flutter_notification_manager 插件允许你创建和管理 Android 通知通道。你可以通过调用 createNotificationChannel() 方法来创建一个通知通道:

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

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

class MyApp extends StatelessWidget {
  [@override](/user/override)
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(title: Text('Flutter Notification Manager Example')),
        body: Center(
          child: ElevatedButton(
            onPressed: () async {
              const notificationManager = NotificationManager();
              await notificationManager.createNotificationChannel(
                NotificationChannel(
                  id: 'my_channel_01',
                  name: 'My First Channel',
                  importance: Importance.standard, // 设置通知的重要性
                ),
              );
              print('Notification channel created');
            },
            child: Text('Create Notification Channel'),
          ),
        ),
      ),
    );
  }
}

2. 读取通知通道设置

你可以通过调用 getNotificationChannel()getNotificationChannels() 方法来读取通知通道的设置:

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

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

class MyApp extends StatelessWidget {
  [@override](/user/override)
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(title: Text('Flutter Notification Manager Example')),
        body: Center(
          child: Column(
            mainAxisAlignment: MainAxisAlignment.center,
            children: [
              ElevatedButton(
                onPressed: () async {
                  const notificationManager = NotificationManager();
                  final myChannel = await notificationManager.getNotificationChannel('my_channel_01');
                  print('Notification channel settings: $myChannel');
                },
                child: Text('Get Notification Channel'),
              ),
              SizedBox(height: 20),
              ElevatedButton(
                onPressed: () async {
                  const notificationManager = NotificationManager();
                  final allChannels = await notificationManager.getNotificationChannels();
                  print('All notification channels: $allChannels');
                },
                child: Text('Get All Notification Channels'),
              ),
            ],
          ),
        ),
      ),
    );
  }
}

3. 删除通知通道

你可以通过调用 deleteNotificationChannel() 方法来删除一个通知通道:

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

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

class MyApp extends StatelessWidget {
  [@override](/user/override)
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(title: Text('Flutter Notification Manager Example')),
        body: Center(
          child: ElevatedButton(
            onPressed: () async {
              const notificationManager = NotificationManager();
              notificationManager.deleteNotificationChannel('my_channel_01');
              print('Notification channel deleted');
            },
            child: Text('Delete Notification Channel'),
          ),
        ),
      ),
    );
  }
}

4. 创建通知通道组

你可以通过调用 createNotificationChannelGroup() 方法来创建一个通知通道组,并将通知通道关联到该组:

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

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

class MyApp extends StatelessWidget {
  [@override](/user/override)
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(title: Text('Flutter Notification Manager Example')),
        body: Center(
          child: Column(
            mainAxisAlignment: MainAxisAlignment.center,
            children: [
              ElevatedButton(
                onPressed: () async {
                  const notificationManager = NotificationManager();
                  const group = NotificationChannelGroup(id: 'my_group_01', name: 'My first group');
                  notificationManager.createNotificationChannelGroup(group);
                  print('Notification channel group created');
                },
                child: Text('Create Notification Channel Group'),
              ),
              SizedBox(height: 20),
              ElevatedButton(
                onPressed: () async {
                  const notificationManager = NotificationManager();
                  await notificationManager.createNotificationChannel(
                    NotificationChannel(
                      id: 'my_channel_02',
                      name: 'My Second Channel',
                      importance: Importance.high,
                      groupId: 'my_group_01', // 关联到已创建的组
                    ),
                  );
                  print('Notification channel with group created');
                },
                child: Text('Create Notification Channel with Group'),
              ),
            ],
          ),
        ),
      ),
    );
  }
}

5. 向后兼容性

flutter_notification_manager 插件的功能取决于 Android SDK 的版本。最低支持的 Android 版本是 8.0(API 级别 26)。以下表格显示了不同 API 级别下可用的操作:

操作 API 26 O API 28 P +
createNotificationChannel
createNotificationChannels
createNotificationChannelGroup
createNotificationChannelGroups
deleteNotificationChannel
getNotificationChannel
getNotificationChannels
getNotificationChannelGroup
getNotificationChannelGroups

6. 错误处理

在 API 级别 25 及以下调用 NotificationManager 的任何方法都不会有任何效果,也不会抛出错误。但是,在创建 NotificationChannelNotificationChannelGroup 时,必须满足以下前提条件:

  • NotificationChannelid 不能为空或空白。
  • NotificationChannelGroupid 不能为空或空白。
  • NotificationChannelimportance 不能为 Importance.unspecified

违反这些条件会导致抛出 PlatformException,错误代码为 INVALID_ARGUMENT。你可能会遇到带有 UNKNOWN 代码的 PlatformException,这通常表示尚未处理的边缘情况。

7. 完整示例 Demo

以下是一个完整的示例应用,展示了如何创建、读取、删除通知通道以及创建通知通道组:

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

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

class MyApp extends StatelessWidget {
  [@override](/user/override)
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(title: Text('Flutter Notification Manager Example')),
        body: Padding(
          padding: const EdgeInsets.all(16.0),
          child: Column(
            mainAxisAlignment: MainAxisAlignment.center,
            children: [
              ElevatedButton(
                onPressed: () async {
                  const notificationManager = NotificationManager();
                  await notificationManager.createNotificationChannel(
                    NotificationChannel(
                      id: 'my_channel_01',
                      name: 'My First Channel',
                      importance: Importance.standard,
                    ),
                  );
                  print('Notification channel created');
                },
                child: Text('Create Notification Channel'),
              ),
              SizedBox(height: 10),
              ElevatedButton(
                onPressed: () async {
                  const notificationManager = NotificationManager();
                  final myChannel = await notificationManager.getNotificationChannel('my_channel_01');
                  print('Notification channel settings: $myChannel');
                },
                child: Text('Get Notification Channel'),
              ),
              SizedBox(height: 10),
              ElevatedButton(
                onPressed: () async {
                  const notificationManager = NotificationManager();
                  final allChannels = await notificationManager.getNotificationChannels();
                  print('All notification channels: $allChannels');
                },
                child: Text('Get All Notification Channels'),
              ),
              SizedBox(height: 10),
              ElevatedButton(
                onPressed: () async {
                  const notificationManager = NotificationManager();
                  notificationManager.deleteNotificationChannel('my_channel_01');
                  print('Notification channel deleted');
                },
                child: Text('Delete Notification Channel'),
              ),
              SizedBox(height: 10),
              ElevatedButton(
                onPressed: () async {
                  const notificationManager = NotificationManager();
                  const group = NotificationChannelGroup(id: 'my_group_01', name: 'My first group');
                  notificationManager.createNotificationChannelGroup(group);
                  print('Notification channel group created');
                },
                child: Text('Create Notification Channel Group'),
              ),
              SizedBox(height: 10),
              ElevatedButton(
                onPressed: () async {
                  const notificationManager = NotificationManager();
                  await notificationManager.createNotificationChannel(
                    NotificationChannel(
                      id: 'my_channel_02',
                      name: 'My Second Channel',
                      importance: Importance.high,
                      groupId: 'my_group_01',
                    ),
                  );
                  print('Notification channel with group created');
                },
                child: Text('Create Notification Channel with Group'),
              ),
            ],
          ),
        ),
      ),
    );
  }
}

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

1 回复

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


当然,以下是如何在Flutter项目中使用flutter_notification_manager插件进行通知管理的示例代码。这个插件允许你处理本地通知和系统通知,并在后台执行某些操作。

1. 添加依赖

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

dependencies:
  flutter:
    sdk: flutter
  flutter_local_notifications: ^9.0.0  # 这个插件通常与flutter_notification_manager一起使用
  flutter_notification_manager: ^0.0.2  # 请检查最新版本号

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.RECEIVE_BOOT_COMPLETED"/>
    <uses-permission android:name="android.permission.FOREGROUND_SERVICE"/>
    <application
        ... >
        
        <receiver android:name="com.dexterous.flutterlocalnotifications.ScheduledNotificationBootReceiver">
            <intent-filter>
                <action android:name="android.intent.action.BOOT_COMPLETED"/>
            </intent-filter>
        </receiver>

        <!-- Add other configurations -->

    </application>
</manifest>

创建MainApplication.kt(如果你使用的是Kotlin)或MainApplication.java(如果你使用的是Java),并配置FlutterNotificationManager

MainApplication.kt

package com.example.yourapp

import io.flutter.embedding.android.FlutterActivity
import io.flutter.embedding.engine.FlutterEngine
import io.flutter.plugins.GeneratedPluginRegistrant
import com.dexterous.flutterlocalnotifications.FlutterLocalNotificationsPlugin
import com.yourapp.flutternotificationmanager.FlutterNotificationManager

class MainApplication: FlutterApplication() {
    override fun onCreate() {
        super.onCreate()
        FlutterNotificationManager.initialize(this, FlutterLocalNotificationsPlugin())
    }

    override fun configureFlutterEngine(flutterEngine: FlutterEngine) {
        super.configureFlutterEngine(flutterEngine)
        GeneratedPluginRegistrant.registerWith(flutterEngine)
    }
}

MainApplication.java

package com.example.yourapp;

import io.flutter.embedding.android.FlutterActivity;
import io.flutter.embedding.engine.FlutterEngine;
import io.flutter.plugins.GeneratedPluginRegistrant;
import com.dexterous.flutterlocalnotifications.FlutterLocalNotificationsPlugin;
import com.yourapp.flutternotificationmanager.FlutterNotificationManager;

import android.app.Application;

public class MainApplication extends Application {
    @Override
    public void onCreate() {
        super.onCreate();
        FlutterNotificationManager.initialize(this, new FlutterLocalNotificationsPlugin());
    }

    @Override
    public void configureFlutterEngine(FlutterEngine flutterEngine) {
        super.configureFlutterEngine(flutterEngine);
        GeneratedPluginRegistrant.registerWith(flutterEngine);
    }
}

iOS

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

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

AppDelegate.swiftAppDelegate.m中配置:

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)
    
    if #available(iOS 10.0, *) {
      UNUserNotificationCenter.current().requestAuthorization(options: [.alert, .sound, .badge]) {
        (granted, error) in
        if let error = error {
          print("Notification authorization error: \(error.localizedDescription)")
        }
      }
    } else {
      let settings: UIUserNotificationSettings =
        UIUserNotificationSettings(types: [.alert, .sound, .badge], categories: nil)
      application.registerUserNotificationSettings(settings)
    }
    
    application.registerForRemoteNotifications()
    
    return super.application(application, didFinishLaunchingWithOptions: launchOptions)
  }
}

AppDelegate.m

#import "AppDelegate.h"
#import <Flutter/Flutter.h>
#import <UserNotifications/UserNotifications.h>

@interface AppDelegate ()
@end

@implementation AppDelegate

- (BOOL)application:(UIApplication *)application
    didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
  [GeneratedPluginRegistrant registerWithRegistry:self];
    
  if (@available(iOS 10.0, *)) {
    [UNUserNotificationCenter currentNotificationCenter].delegate = self;
    [[UNUserNotificationCenter currentNotificationCenter] requestAuthorizationWithOptions:(UNAuthorizationOptionsAlert | UNAuthorizationOptionsSound | UNAuthorizationOptionsBadge)
                                                                      completionHandler:^(BOOL granted, NSError * _Nullable error) {
        if (error != nil) {
          NSLog(@"Notification authorization error: %@", error.localizedDescription);
        }
      }];
  } else {
    UIUserNotificationType allNotificationTypes =
    (UIUserNotificationTypeAlert | UIUserNotificationTypeSound | UIUserNotificationTypeBadge);
    UIUserNotificationSettings *settings =
    [UIUserNotificationSettings settingsForTypes:allNotificationTypes categories:nil];
    [application registerUserNotificationSettings:settings];
  }
  
  [application registerForRemoteNotifications];
  
  return [super application:application didFinishLaunchingWithOptions:launchOptions];
}

@end

3. 使用Flutter代码配置通知

在你的Dart代码中,初始化并配置通知:

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

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

class MyApp extends StatelessWidget {
  [@override](/user/override)
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: Text('Flutter Notification Manager Demo'),
        ),
        body: NotificationPage(),
      ),
    );
  }
}

class NotificationPage extends StatefulWidget {
  [@override](/user/override)
  _NotificationPageState createState() => _NotificationPageState();
}

class _NotificationPageState extends State<NotificationPage> {
  final FlutterLocalNotificationsPlugin flutterLocalNotificationsPlugin = FlutterLocalNotificationsPlugin();
  var initializationSettingsAndroid;
  var initializationSettingsIOS;
  var initializationSettings;

  [@override](/user/override)
  void initState() {
    super.initState();
    var androidChannelSpecifics = AndroidNotificationDetails(
      'your_channel_id',
      'Your channel name',
      'Your channel description',
      importance: Importance.max,
      priority: Priority.high,
    );
    var iOSChannelSpecifics = IOSNotificationDetails();

    initializationSettingsAndroid = AndroidInitializationSettings('@mipmap/ic_launcher');
    initializationSettingsIOS = IOSInitializationSettings(
      requestAlertPermission: true,
      requestBadgePermission: true,
      requestSoundPermission: true,
    );
    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',
      playSound: true,
      sound: RawResourceAndroidNotificationSound('notification_sound'),
      importance: Importance.max,
      priority: Priority.high,
    );
    var iOSPlatformChannelSpecifics = IOSNotificationDetails();

    NotificationDetails 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
回到顶部