flutter_local_notifications最简单示例

2023-04-25  本文已影响0人  leptune

根据flutter_local_notifications13.0.0的官方示例代码简化修改的:


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

class NotificationService {
  final FlutterLocalNotificationsPlugin _flutterLocalNotificationsPlugin = FlutterLocalNotificationsPlugin();
  /// 创建流以便应用程序可以响应与通知相关的事件,因为插件是在 main 函数中初始化的。
  final StreamController<String?> _selectNotificationStream = StreamController<String?>.broadcast();

  static final NotificationService _singleton = NotificationService._internal();
  factory NotificationService() {
    return _singleton;
  }
  NotificationService._internal();

  Future<void> init() async {
    await _flutterLocalNotificationsPlugin.getNotificationAppLaunchDetails();
    const AndroidInitializationSettings initializationSettingsAndroid =
    AndroidInitializationSettings('app_icon');

    /// 这里没有请求权限
    final DarwinInitializationSettings initializationSettingsDarwin =
    DarwinInitializationSettings(
      requestAlertPermission: false,
      requestBadgePermission: false,
      requestSoundPermission: false,
      onDidReceiveLocalNotification:
          (int id, String? title, String? body, String? payload) async {},
    );
    final InitializationSettings initializationSettings = InitializationSettings(
      android: initializationSettingsAndroid,
      iOS: initializationSettingsDarwin,
    );
    await _flutterLocalNotificationsPlugin.initialize(initializationSettings,
        onDidReceiveNotificationResponse:
            (NotificationResponse notificationResponse) {
          switch (notificationResponse.notificationResponseType) {
            case NotificationResponseType.selectedNotification:
              _selectNotificationStream.add(notificationResponse.payload);
              break;
            case NotificationResponseType.selectedNotificationAction:
              break;
          }
        });
  }

  Future<void> requestPermissions() async {
    if (Platform.isIOS || Platform.isMacOS) {
      await _flutterLocalNotificationsPlugin
          .resolvePlatformSpecificImplementation<
          IOSFlutterLocalNotificationsPlugin>()
          ?.requestPermissions(
        alert: true,
        badge: true,
        sound: true,
      );
      await _flutterLocalNotificationsPlugin
          .resolvePlatformSpecificImplementation<
          MacOSFlutterLocalNotificationsPlugin>()
          ?.requestPermissions(
        alert: true,
        badge: true,
        sound: true,
      );
    } else if (Platform.isAndroid) {
      final AndroidFlutterLocalNotificationsPlugin? androidImplementation =
      _flutterLocalNotificationsPlugin
          .resolvePlatformSpecificImplementation<
          AndroidFlutterLocalNotificationsPlugin>();

      await androidImplementation?.requestPermission();
    }
  }

  void configureSelectNotificationSubject(BuildContext context) {
    _selectNotificationStream.stream.listen((String? payload) {
      if (payload != null && payload.isNotEmpty) {
        Navigator.of(context).pushNamed(payload);
      }
    });
  }

  Future<void> showNotification() async {
    const AndroidNotificationDetails androidNotificationDetails =
    AndroidNotificationDetails('your channel id', 'your channel name',
        channelDescription: '你的频道描述',
        importance: Importance.max,
        priority: Priority.high,
        ticker: 'ticker');
    // iOS 通知配置
    // const DarwinNotificationDetails iosNotificationDetails = DarwinNotificationDetails(
    //   presentAlert: false, // 显示通知
    //   presentBadge: false,  // 在应用图标上显示通知标记
    //   presentSound: false,  // 播放通知声音
    // );
    const NotificationDetails notificationDetails = NotificationDetails(
      android: androidNotificationDetails,
      // iOS: iosNotificationDetails,
    );
    await _flutterLocalNotificationsPlugin.show(
        0, null, '通知内容', notificationDetails,
        payload: '/secondPage');
  }
}

Future<void> main() async {
  WidgetsFlutterBinding.ensureInitialized();
  final notificationService = NotificationService();
  await notificationService.init();

  runApp(
    MaterialApp(
      initialRoute: HomePage.routeName,
      routes: <String, WidgetBuilder>{
        HomePage.routeName: (_) =>
            HomePage(notificationService: notificationService),
        SecondPage.routeName: (_) => const SecondPage()
      },
    ),
  );
}

class HomePage extends StatefulWidget {
  const HomePage({
    Key? key,
    required this.notificationService,
  }) : super(key: key);

  static const String routeName = '/';
  final NotificationService notificationService;

  @override
  State<HomePage> createState() => _HomePageState();
}

class _HomePageState extends State<HomePage> {
  @override
  void initState() {
    super.initState();
    widget.notificationService.requestPermissions();
    widget.notificationService.configureSelectNotificationSubject(context);
  }

  @override
  Widget build(BuildContext context) => Scaffold(
    appBar: AppBar(
      title: const Text('插件示例应用'),
    ),
    body: Padding(
      padding: const EdgeInsets.all(8),
      child: ElevatedButton(
        child: const Text('显示没有标题且带有数据的普通通知'),
        onPressed: () async {
          await widget.notificationService.showNotification();
        },
      ),
    ),
  );
}

class SecondPage extends StatefulWidget {
  const SecondPage({
    Key? key,
    this.payload,
  }) : super(key: key);

  static const String routeName = '/secondPage';
  final String? payload;
  @override
  State<StatefulWidget> createState() => SecondPageState();
}

class SecondPageState extends State<SecondPage> {
  @override
  void initState() {
    super.initState();
  }

  @override
  Widget build(BuildContext context) => Scaffold(
    appBar: AppBar(
      title: const Text('第二个屏幕'),
    ),
    body: Center(
      child: Column(
        mainAxisSize: MainAxisSize.min,
        children: <Widget>[
          ElevatedButton(
            onPressed: () {
              Navigator.pop(context);
            },
            child: const Text('返回!'),
          ),
        ],
      ),
    ),
  );
}

ios修改ios/Runner/AppDelegate.m如下:

#import "AppDelegate.h"
#import "GeneratedPluginRegistrant.h"
// This is required for calling FlutterLocalNotificationsPlugin.setPluginRegistrantCallback method.
#import <FlutterLocalNotificationsPlugin.h>

void registerPlugins(NSObject<FlutterPluginRegistry>* registry) {
    [GeneratedPluginRegistrant registerWithRegistry:registry];
}

@implementation AppDelegate

- (BOOL)application:(UIApplication *)application
    didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {

   if (@available(iOS 10.0, *)) {
      [UNUserNotificationCenter currentNotificationCenter].delegate = (id<UNUserNotificationCenterDelegate>) self;
   }

  [GeneratedPluginRegistrant registerWithRegistry:self];

  // Add this method
  [FlutterLocalNotificationsPlugin setPluginRegistrantCallback:registerPlugins];

  // Override point for customization after application launch.
  return [super application:application didFinishLaunchingWithOptions:launchOptions];
}

// 在前台收到通知时展示通知
- (void)userNotificationCenter:(UNUserNotificationCenter *)center
       willPresentNotification:(UNNotification *)notification
         withCompletionHandler:(void (^)(UNNotificationPresentationOptions options))completionHandler
{
  completionHandler(UNNotificationPresentationOptionSound | UNNotificationPresentationOptionAlert | UNNotificationPresentationOptionBadge);
}

@end

ios修改ios/Runner/Info.plist如下:

<key>UIBackgroundModes</key>
    <array>
      <string>fetch</string>
      <string>remote-notification</string>
    </array>
    <key>NSAppTransportSecurity</key>
    <dict>
        <key>NSAllowsArbitraryLoads</key>
        <true/>
    </dict>
上一篇下一篇

猜你喜欢

热点阅读