1.初始化flutter_local_notifications插件。
final FlutterLocalNotificationsPlugin flutterLocalNotificationsPlugin =
FlutterLocalNotificationsPlugin();
Future<void> initializeNotifications() async {
const AndroidInitializationSettings initializationSettingsAndroid =
AndroidInitializationSettings("@mipmap/ic_launcher");
const InitializationSettings initializationSettings = InitializationSettings(
android: initializationSettingsAndroid);
await flutterLocalNotificationsPlugin.initialize(initializationSettings);
}
2.在main函数中调用初始化操作
Future<void> main() async {
//初始化操作
WidgetsFlutterBinding.ensureInitialized();
initializeNotifications();
tz.initializeTimeZones();
//获取当前设备所处时区
final String currentTimeZone = await FlutterTimezone.getLocalTimezone();
Tool.currentTimeZone=currentTimeZone;
runApp(const MyApp();
}
3.写一个NotificationHelper类
import 'package:flutter/cupertino.dart';
import 'package:flutter_local_notifications/flutter_local_notifications.dart';
import 'package:timezone/timezone.dart' as tz;
import '../main.dart';
import '../tools/tool.dart';
class NotificationHelper extends StatefulWidget {
String name;
String body;
int hour;
int min;
int id;
NotificationHelper(
{super.key,
required this.name,
required this.body,
required this.hour,
required this.min,
required this.id});
Future<void> scheduleNotification() async {
const AndroidNotificationDetails androidPlatformChannelSpecifics =
AndroidNotificationDetails(
'channel_id',
'channel_name',
'channel_description',
importance: Importance.max,
priority: Priority.high,
);
const NotificationDetails platformChannelSpecifics =
NotificationDetails(android: androidPlatformChannelSpecifics);
final now = DateTime.now();
//推送的时间
final scheduledDate = DateTime(now.year, now.month, now.day, hour, min);
await flutterLocalNotificationsPlugin.zonedSchedule(
//id唯一
id,
name,
type,
//计算推送时间
_nextInstanceOfTime(scheduledDate),
platformChannelSpecifics,
androidAllowWhileIdle: true,
uiLocalNotificationDateInterpretation:
UILocalNotificationDateInterpretation.absoluteTime,
//每周重复一次
// matchDateTimeComponents: DateTimeComponents.dayOfWeekAndTime
//每天重复一次
//matchDateTimeComponents: DateTimeComponents.time
//每个月重复一次
//matchDateTimeComponents: DateTimeComponents.dayOfMonthAndTime);
//每年重复一次
//matchDateTimeComponents: DateTimeComponents.dateAndTime
);
}
tz.TZDateTime _nextInstanceOfTime(DateTime scheduledTime) {
//获取手机当前时区的时间
tz.TZDateTime now = tz.TZDateTime.now(tz.getLocation(Tool.currentTimeZone));
tz.TZDateTime scheduledDate = tz.TZDateTime(
tz.getLocation(Tool.currentTimeZone),
now.year,
now.month,
now.day,
scheduledTime.hour,
scheduledTime.minute,
);
if (scheduledDate.isBefore(now)) {
scheduledDate = scheduledDate.add(const Duration(days:1));
}
return scheduledDate;
}
State<StatefulWidget> createState() {
// TODO: implement createState
throw UnimplementedError();
}
}
4.调用
NotificationHelper(
name: xx,
body:xx,
hour: xx,
min: xx,
id: xx,
).scheduleNotification();