Flutter 中的本地通知:定时提醒的实现

Flutter 中的本地通知:定时提醒的实现

5 回复

使用flutter_local_notifications插件实现,配置定时时间与内容即可。

更多关于Flutter 中的本地通知:定时提醒的实现的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html


在Flutter中,使用flutter_local_notifications插件实现定时提醒。设置AndroidNotificationDetailsiOSNotificationDetails,并通过zonedSchedule方法指定触发时间。

在 Flutter 中实现本地定时通知,可以使用 flutter_local_notifications 插件。首先,添加依赖到 pubspec.yaml 文件。然后,初始化插件并设置 Android 和 iOS 的配置。使用 zonedSchedule 方法可以设置定时通知,指定触发时间和通知内容。确保在应用启动时初始化插件,并在需要时请求通知权限。

使用flutter_local_notifications插件设置定时通知。

在 Flutter 中,可以使用 flutter_local_notifications 插件来实现本地通知,包括定时提醒。以下是一个简单的示例,展示如何设置定时通知。

1. 添加依赖

首先,在 pubspec.yaml 文件中添加 flutter_local_notifications 依赖:

dependencies:
  flutter:
    sdk: flutter
  flutter_local_notifications: ^9.5.3

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

2. 初始化插件

main.dart 中初始化 flutter_local_notifications 插件:

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

final FlutterLocalNotificationsPlugin flutterLocalNotificationsPlugin =
    FlutterLocalNotificationsPlugin();

void main() async {
  WidgetsFlutterBinding.ensureInitialized();

  const AndroidInitializationSettings initializationSettingsAndroid =
      AndroidInitializationSettings('@mipmap/ic_launcher');

  final InitializationSettings initializationSettings =
      InitializationSettings(android: initializationSettingsAndroid);

  await flutterLocalNotificationsPlugin.initialize(initializationSettings);

  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(title: Text('Local Notification Example')),
        body: Center(
          child: ElevatedButton(
            onPressed: () => scheduleNotification(),
            child: Text('Schedule Notification'),
          ),
        ),
      ),
    );
  }
}

3. 设置定时通知

添加一个函数来设置定时通知。以下示例展示了如何设置一个在 5 秒后触发的通知:

Future<void> scheduleNotification() async {
  const AndroidNotificationDetails androidPlatformChannelSpecifics =
      AndroidNotificationDetails(
    'your channel id',
    'your channel name',
    importance: Importance.max,
    priority: Priority.high,
  );

  const NotificationDetails platformChannelSpecifics =
      NotificationDetails(android: androidPlatformChannelSpecifics);

  await flutterLocalNotificationsPlugin.zonedSchedule(
    0,
    'Scheduled Notification',
    'This is a scheduled notification',
    tz.TZDateTime.now(tz.local).add(const Duration(seconds: 5)),
    platformChannelSpecifics,
    androidAllowWhileIdle: true,
    uiLocalNotificationDateInterpretation:
        UILocalNotificationDateInterpretation.absoluteTime,
  );
}

4. 运行应用

运行应用后,点击按钮将触发一个在 5 秒后显示的通知。

注意事项

  • 你可以根据需要调整通知的触发时间和内容。
  • flutter_local_notifications 插件还支持其他平台(如 iOS),但配置方式有所不同。
  • 如果需要更复杂的定时任务,可以考虑结合 android_alarm_managerworkmanager 插件使用。
回到顶部