flutter_local_notifications最簡單示例

根據(jù)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();
  /// 創(chuàng)建流以便應(yīng)用程序可以響應(yīng)與通知相關(guān)的事件,因?yàn)椴寮窃?main 函數(shù)中初始化的侦副。
  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');

    /// 這里沒有請求權(quán)限
    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,  // 在應(yīng)用圖標(biāo)上顯示通知標(biāo)記
    //   presentSound: false,  // 播放通知聲音
    // );
    const NotificationDetails notificationDetails = NotificationDetails(
      android: androidNotificationDetails,
      // iOS: iosNotificationDetails,
    );
    await _flutterLocalNotificationsPlugin.show(
        0, null, '通知內(nèi)容', 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('插件示例應(yīng)用'),
    ),
    body: Padding(
      padding: const EdgeInsets.all(8),
      child: ElevatedButton(
        child: const Text('顯示沒有標(biāo)題且?guī)в袛?shù)據(jù)的普通通知'),
        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('第二個(gè)屏幕'),
    ),
    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];
}

// 在前臺收到通知時(shí)展示通知
- (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>
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末赋除,一起剝皮案震驚了整個(gè)濱河市,隨后出現(xiàn)的幾起案子诉植,更是在濱河造成了極大的恐慌蟋定,老刑警劉巖张弛,帶你破解...
    沈念sama閱讀 223,002評論 6 519
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件,死亡現(xiàn)場離奇詭異意推,居然都是意外死亡豆瘫,警方通過查閱死者的電腦和手機(jī),發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 95,357評論 3 400
  • 文/潘曉璐 我一進(jìn)店門菊值,熙熙樓的掌柜王于貴愁眉苦臉地迎上來外驱,“玉大人,你說我怎么就攤上這事腻窒£怯睿” “怎么了?”我有些...
    開封第一講書人閱讀 169,787評論 0 365
  • 文/不壞的土叔 我叫張陵儿子,是天一觀的道長瓦哎。 經(jīng)常有香客問我,道長柔逼,這世上最難降的妖魔是什么蒋譬? 我笑而不...
    開封第一講書人閱讀 60,237評論 1 300
  • 正文 為了忘掉前任,我火速辦了婚禮愉适,結(jié)果婚禮上犯助,老公的妹妹穿的比我還像新娘。我一直安慰自己维咸,他們只是感情好剂买,可當(dāng)我...
    茶點(diǎn)故事閱讀 69,237評論 6 398
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著癌蓖,像睡著了一般瞬哼。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發(fā)上费坊,一...
    開封第一講書人閱讀 52,821評論 1 314
  • 那天倒槐,我揣著相機(jī)與錄音旬痹,去河邊找鬼附井。 笑死讨越,一個(gè)胖子當(dāng)著我的面吹牛,可吹牛的內(nèi)容都是我干的永毅。 我是一名探鬼主播把跨,決...
    沈念sama閱讀 41,236評論 3 424
  • 文/蒼蘭香墨 我猛地睜開眼,長吁一口氣:“原來是場噩夢啊……” “哼沼死!你這毒婦竟也來了着逐?” 一聲冷哼從身側(cè)響起,我...
    開封第一講書人閱讀 40,196評論 0 277
  • 序言:老撾萬榮一對情侶失蹤意蛀,失蹤者是張志新(化名)和其女友劉穎耸别,沒想到半個(gè)月后,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體县钥,經(jīng)...
    沈念sama閱讀 46,716評論 1 320
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡秀姐,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 38,794評論 3 343
  • 正文 我和宋清朗相戀三年,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了若贮。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片省有。...
    茶點(diǎn)故事閱讀 40,928評論 1 353
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡,死狀恐怖谴麦,靈堂內(nèi)的尸體忽然破棺而出蠢沿,到底是詐尸還是另有隱情,我是刑警寧澤匾效,帶...
    沈念sama閱讀 36,583評論 5 351
  • 正文 年R本政府宣布舷蟀,位于F島的核電站,受9級特大地震影響面哼,放射性物質(zhì)發(fā)生泄漏雪侥。R本人自食惡果不足惜,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 42,264評論 3 336
  • 文/蒙蒙 一精绎、第九天 我趴在偏房一處隱蔽的房頂上張望速缨。 院中可真熱鬧,春花似錦代乃、人聲如沸旬牲。這莊子的主人今日做“春日...
    開封第一講書人閱讀 32,755評論 0 25
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽原茅。三九已至,卻和暖如春堕仔,著一層夾襖步出監(jiān)牢的瞬間擂橘,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 33,869評論 1 274
  • 我被黑心中介騙來泰國打工摩骨, 沒想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留通贞,地道東北人朗若。 一個(gè)月前我還...
    沈念sama閱讀 49,378評論 3 379
  • 正文 我出身青樓,卻偏偏與公主長得像昌罩,于是被迫代替她去往敵國和親哭懈。 傳聞我的和親對象是個(gè)殘疾皇子,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 45,937評論 2 361

推薦閱讀更多精彩內(nèi)容