Hello, I’m Shendi
整了好久,记录一下
# 系统通知插件
flutter_local_notifications: ^9.1.5
在 dart 中导入
import 'package:flutter_local_notifications/flutter_local_notifications.dart';
首先需要创建通知插件
final FlutterLocalNotificationsPlugin np = FlutterLocalNotificationsPlugin();
然后初始化 Android、IOS的设置
/// 这里的参数为Android通知的图标路径-必须,其中 @mipmap 对应android app->src->main->res->mipmap 文件夹
var android = const AndroidInitializationSettings("@mipmap/logo");
var ios = const IOSInitializationSettings();
np.initialize(InitializationSettings(android: android, iOS: ios));
var androidDetails = const AndroidNotificationDetails(
'id 描述',
'名称描述',
importance: Importance.max,
priority: Priority.high
);
var iosDetails = const IOSNotificationDetails();
var details = NotificationDetails(
android: androidDetails,
iOS: iosDetails
);
// 显示通知
// 第一个参数是id,id如果一致则会覆盖之前的通知
// 第二个参数是通知标题
// 第三个参数通知内容,最后一个参数为上面步骤的描述
np.show(DateTime.now().millisecondsSinceEpoch >> 10, title, body, details);
/// 通知封装
/// author Shendi
class Notification {
final FlutterLocalNotificationsPlugin np = FlutterLocalNotificationsPlugin();
/// 是否初始化了
var isInit = false;
/// 初始化
void init() {
if (isInit) return;
isInit = true;
var android = const AndroidInitializationSettings("@mipmap/logo");
var ios = const IOSInitializationSettings();
np.initialize(InitializationSettings(android: android, iOS: ios));
}
void send(String title, String body) {
// 初始化
init();
// 构建描述
var androidDetails = const AndroidNotificationDetails(
'id描述',
'名称描述',
importance: Importance.max,
priority: Priority.high
);
var iosDetails = const IOSNotificationDetails();
var details = NotificationDetails(
android: androidDetails,
iOS: iosDetails
);
// 显示通知, 第一个参数是id,id如果一致则会覆盖之前的通知
np.show(DateTime.now().millisecondsSinceEpoch >> 10, title, body, details);
}
}
var notification = Notification();
将上面代码拷贝到项目内,使用 notification.send(通知标题,通知内容); 来发送通知