Flutter本地通知插件fatih_local_notifications的使用

好的,以下是根据您提供的内容整理的关于“Flutter本地通知插件fatih_local_notifications的使用”的详细内容和示例代码。我们将严格按照您的要求进行处理。

Flutter本地通知插件fatih_local_notifications的使用

简介

flutter_local_notifications 是一个跨平台的插件,用于在应用中显示本地通知。

import 'package:flutter_local_notifications/flutter_local_notifications.dart';

安装

在项目的 pubspec.yaml 文件中添加依赖:

dependencies:
  flutter_local_notifications: ^9.0.0

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

初始化

首先创建并初始化 FlutterLocalNotificationsPlugin 实例,并设置相应的配置。

final FlutterLocalNotificationsPlugin flutterLocalNotificationsPlugin = FlutterLocalNotificationsPlugin();

const AndroidInitializationSettings initializationSettingsAndroid = AndroidInitializationSettings('app_icon');
final DarwinInitializationSettings initializationSettingsDarwin = DarwinInitializationSettings(
  onDidReceiveLocalNotification: onDidReceiveLocalNotification,
);
final LinuxInitializationSettings initializationSettingsLinux = LinuxInitializationSettings(
  defaultActionName: 'Open notification',
);
final InitializationSettings initializationSettings = InitializationSettings(
  android: initializationSettingsAndroid,
  iOS: initializationSettingsDarwin,
  macOS: initializationSettingsDarwin,
  linux: initializationSettingsLinux,
);

await flutterLocalNotificationsPlugin.initialize(
  initializationSettings,
  onDidReceiveNotificationResponse: onDidReceiveNotificationResponse,
);

显示通知

以下是如何显示一个简单的通知。

Future<void> showSimpleNotification() async {
  const AndroidNotificationDetails androidNotificationDetails = AndroidNotificationDetails(
    'your channel id', 'your channel name',
    channelDescription: 'your channel description',
    importance: Importance.max,
    priority: Priority.high,
    ticker: 'ticker',
  );
  const NotificationDetails notificationDetails = NotificationDetails(android: androidNotificationDetails);
  await flutterLocalNotificationsPlugin.show(
    0, 'plain title', 'plain body', notificationDetails,
    payload: 'item x',
  );
}

定时通知

可以使用 zonedSchedule 方法来安排通知。

Future<void> scheduleNotification() async {
  await flutterLocalNotificationsPlugin.zonedSchedule(
    0,
    'scheduled title',
    'scheduled body',
    tz.TZDateTime.now(tz.local).add(const Duration(seconds: 5)),
    const NotificationDetails(
      android: AndroidNotificationDetails(
        'your channel id', 'your channel name',
        channelDescription: 'your channel description',
      ),
    ),
    androidAllowWhileIdle: true,
    uiLocalNotificationDateInterpretation: UILocalNotificationDateInterpretation.absoluteTime,
  );
}

分组通知

在 Android 中,可以将多个通知分组。

Future<void> showGroupedNotifications() async {
  const String groupKey = 'com.android.example.WORK_EMAIL';
  const String groupChannelId = 'grouped channel id';
  const String groupChannelName = 'grouped channel name';
  const String groupChannelDescription = 'grouped channel description';

  const AndroidNotificationDetails firstNotificationAndroidSpecifics = AndroidNotificationDetails(
    groupChannelId, groupChannelName,
    channelDescription: groupChannelDescription,
    importance: Importance.max,
    priority: Priority.high,
    groupKey: groupKey,
  );
  const NotificationDetails firstNotificationPlatformSpecifics = NotificationDetails(android: firstNotificationAndroidSpecifics);
  await flutterLocalNotificationsPlugin.show(1, 'Alex Faarborg', 'You will not believe...', firstNotificationPlatformSpecifics);

  const AndroidNotificationDetails secondNotificationAndroidSpecifics = AndroidNotificationDetails(
    groupChannelId, groupChannelName,
    channelDescription: groupChannelDescription,
    importance: Importance.max,
    priority: Priority.high,
    groupKey: groupKey,
  );
  const NotificationDetails secondNotificationPlatformSpecifics = NotificationDetails(android: secondNotificationAndroidSpecifics);
  await flutterLocalNotificationsPlugin.show(2, 'Jeff Chang', 'Please join us to celebrate the...', secondNotificationPlatformSpecifics);

  const List<String> lines = ['Alex Faarborg Check this out', 'Jeff Chang Launch Party'];
  const InboxStyleInformation inboxStyleInformation = InboxStyleInformation(lines, contentTitle: '2 messages', summaryText: 'janedoe@example.com');
  const AndroidNotificationDetails androidNotificationDetails = AndroidNotificationDetails(
    groupChannelId, groupChannelName,
    channelDescription: groupChannelDescription,
    styleInformation: inboxStyleInformation,
    groupKey: groupKey,
    setAsGroupSummary: true,
  );
  const NotificationDetails notificationDetails = NotificationDetails(android: androidNotificationDetails);
  await flutterLocalNotificationsPlugin.show(3, 'Attention', 'Two messages', notificationDetails);
}

取消通知

取消特定的通知或所有通知。

Future<void> cancelNotification() async {
  await flutterLocalNotificationsPlugin.cancel(0);
}

Future<void> cancelAllNotifications() async {
  await flutterLocalNotificationsPlugin.cancelAll();
}

完整示例

下面是完整的示例代码,展示如何使用 flutter_local_notifications 插件。

import 'dart:async';
import 'dart:convert';
import 'dart:io';
import 'dart:typed_data';

import 'package:flutter/material.dart';
import 'package:flutter_local_notifications/flutter_local_notifications.dart';
import 'package:timezone/data/latest_all.dart' as tz;
import 'package:timezone/timezone.dart' as tz;

int id = 0;

final FlutterLocalNotificationsPlugin flutterLocalNotificationsPlugin = FlutterLocalNotificationsPlugin();

Future<void> main() async {
  WidgetsFlutterBinding.ensureInitialized();
  await _configureLocalTimeZone();

  await flutterLocalNotificationsPlugin.initialize(
    InitializationSettings(
      android: AndroidInitializationSettings('app_icon'),
      iOS: DarwinInitializationSettings(
        onDidReceiveLocalNotification: onDidReceiveLocalNotification,
      ),
      macOS: DarwinInitializationSettings(
        onDidReceiveLocalNotification: onDidReceiveLocalNotification,
      ),
      linux: LinuxInitializationSettings(
        defaultActionName: 'Open notification',
      ),
    ),
    onDidReceiveNotificationResponse: (NotificationResponse notificationResponse) {
      switch (notificationResponse.notificationResponseType) {
        case NotificationResponseType.selectedNotification:
          selectNotificationStream.add(notificationResponse.payload);
          break;
        case NotificationResponseType.selectedNotificationAction:
          if (notificationResponse.actionId == 'navigationActionId') {
            selectNotificationStream.add(notificationResponse.payload);
          }
          break;
      }
    },
    onDidReceiveBackgroundNotificationResponse: notificationTapBackground,
  );

  runApp(MyApp());
}

Future<void> _configureLocalTimeZone() async {
  if (!kIsWeb && Platform.isLinux) {
    return;
  }
  tz.initializeTimeZones();
  final String? timeZoneName = await FlutterTimezone.getLocalTimezone();
  tz.setLocalLocation(tz.getLocation(timeZoneName!));
}

void onDidReceiveLocalNotification(int id, String? title, String? body, String? payload) async {
  // 处理接收到的通知
}

void notificationTapBackground(NotificationResponse notificationResponse) {
  // 处理后台点击通知事件
}

class MyApp extends StatelessWidget {
  [@override](/user/override)
  Widget build(BuildContext context) {
    return MaterialApp(
      home: HomePage(),
    );
  }
}

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

class _HomePageState extends State<HomePage> {
  [@override](/user/override)
  void initState() {
    super.initState();
    _requestPermissions();
    _configureDidReceiveLocalNotificationSubject();
    _configureSelectNotificationSubject();
  }

  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>();
      final bool? granted = await androidImplementation?.requestPermission();
      setState(() {
        _notificationsEnabled = granted ?? false;
      });
    }
  }

  void _configureDidReceiveLocalNotificationSubject() {
    didReceiveLocalNotificationStream.stream.listen((ReceivedNotification receivedNotification) async {
      await showDialog(
        context: context,
        builder: (BuildContext context) => CupertinoAlertDialog(
          title: receivedNotification.title != null ? Text(receivedNotification.title!) : null,
          content: receivedNotification.body != null ? Text(receivedNotification.body!) : null,
          actions: <Widget>[
            CupertinoDialogAction(
              isDefaultAction: true,
              onPressed: () async {
                Navigator.of(context, rootNavigator: true).pop();
                await Navigator.of(context).push(
                  MaterialPageRoute<void>(
                    builder: (BuildContext context) => SecondPage(receivedNotification.payload),
                  ),
                );
              },
              child: const Text('Ok'),
            )
          ],
        ),
      );
    });
  }

  void _configureSelectNotificationSubject() {
    selectNotificationStream.stream.listen((String? payload) async {
      await Navigator.of(context).push(MaterialPageRoute<void>(
        builder: (BuildContext context) => SecondPage(payload),
      ));
    });
  }

  [@override](/user/override)
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('Plugin example app'),
      ),
      body: SingleChildScrollView(
        child: Padding(
          padding: const EdgeInsets.all(8),
          child: Center(
            child: Column(
              children: <Widget>[
                const Padding(
                  padding: EdgeInsets.fromLTRB(0, 0, 0, 8),
                  child: Text('Tap on a notification when it appears to trigger navigation'),
                ),
                ElevatedButton(
                  onPressed: showSimpleNotification,
                  child: Text('Show simple notification'),
                ),
                ElevatedButton(
                  onPressed: scheduleNotification,
                  child: Text('Schedule notification'),
                ),
                ElevatedButton(
                  onPressed: showGroupedNotifications,
                  child: Text('Show grouped notifications'),
                ),
                ElevatedButton(
                  onPressed: cancelNotification,
                  child: Text('Cancel notification'),
                ),
                ElevatedButton(
                  onPressed: cancelAllNotifications,
                  child: Text('Cancel all notifications'),
                ),
              ],
            ),
          ),
        ),
      ),
    );
  }
}

class SecondPage extends StatefulWidget {
  final String? payload;

  SecondPage(this.payload, {Key? key}) : super(key: key);

  [@override](/user/override)
  _SecondPageState createState() => _SecondPageState();
}

class _SecondPageState extends State<SecondPage> {
  [@override](/user/override)
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('Second Screen'),
      ),
      body: Center(
        child: Column(
          mainAxisSize: MainAxisSize.min,
          children: <Widget>[
            Text('Payload: ${widget.payload ?? ''}'),
            ElevatedButton(
              onPressed: () {
                Navigator.pop(context);
              },
              child: const Text('Go back!'),
            ),
          ],
        ),
      ),
    );
  }
}

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

1 回复

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


fatih_local_notifications 是一个用于在 Flutter 应用中显示本地通知的插件。它允许你在应用的前台或后台发送通知,并且可以自定义通知的外观和行为。

安装插件

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

dependencies:
  flutter:
    sdk: flutter
  fatih_local_notifications: ^1.0.0  # 请检查最新版本

然后运行 flutter pub get 来安装插件。

基本用法

  1. 初始化插件

    在使用插件之前,你需要在应用的 main 函数中初始化插件:

    import 'package:fatih_local_notifications/fatih_local_notifications.dart';
    
    void main() async {
      WidgetsFlutterBinding.ensureInitialized();
      await FatihLocalNotifications.initialize();
      runApp(MyApp());
    }
    
  2. 发送通知

    你可以使用 FatihLocalNotifications.showNotification 方法来发送通知:

    FatihLocalNotifications.showNotification(
      id: 1,
      title: 'Hello',
      body: 'This is a local notification',
      payload: 'notification_payload',
    );
    
    • id: 通知的唯一标识符。
    • title: 通知的标题。
    • body: 通知的内容。
    • payload: 通知的附加数据,可以在用户点击通知时获取。
  3. 处理通知点击事件

    你可以通过 FatihLocalNotifications.onNotificationClick 来监听通知的点击事件:

    FatihLocalNotifications.onNotificationClick.listen((payload) {
      print('Notification clicked with payload: $payload');
    });
    
  4. 自定义通知

    你可以自定义通知的图标、声音、振动等属性:

    FatihLocalNotifications.showNotification(
      id: 2,
      title: 'Custom Notification',
      body: 'This is a custom notification',
      payload: 'custom_notification_payload',
      sound: 'notification_sound.mp3',
      vibration: true,
      icon: 'app_icon',
    );
    
  5. 取消通知

    你可以通过 FatihLocalNotifications.cancelNotification 方法来取消某个通知:

    FatihLocalNotifications.cancelNotification(1);
    
  6. 取消所有通知

    你可以通过 FatihLocalNotifications.cancelAllNotifications 方法来取消所有通知:

    FatihLocalNotifications.cancelAllNotifications();
    

示例代码

以下是一个完整的示例代码,展示了如何使用 fatih_local_notifications 插件:

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

void main() async {
  WidgetsFlutterBinding.ensureInitialized();
  await FatihLocalNotifications.initialize();
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  [@override](/user/override)
  Widget build(BuildContext context) {
    return MaterialApp(
      home: NotificationScreen(),
    );
  }
}

class NotificationScreen extends StatelessWidget {
  [@override](/user/override)
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Local Notifications'),
      ),
      body: Center(
        child: ElevatedButton(
          onPressed: () {
            FatihLocalNotifications.showNotification(
              id: 1,
              title: 'Hello',
              body: 'This is a local notification',
              payload: 'notification_payload',
            );
          },
          child: Text('Show Notification'),
        ),
      ),
    );
  }
}
回到顶部