本机开发环境:flutter 2.10.0 sdk时无法下载最新 ^9.6.0版本的插件,这里更新到了3.0
不更新3.0的话么,可以尝试使用9.1.6版本,我在尝试时发现一些错误,missing plugin error..索性直接更新到了flutter sdk3.0.0版本
Flutter 3.0.1 • channel stable • https:
Framework • revision fb57da5f94 (3 weeks ago) • 2022-05-19 15:50:29 -0700
Engine • revision caaafc5604
Tools • Dart 2.17.1 • DevTools 2.12.2
使用:引入插件flutter_local_notifications: ^9.6.0
dependencies:
flutter_local_notifications: ^9.6.0
在dart中引用
import 'package:flutter_local_notifications/flutter_local_notifications.dart';
代码封装:notificationUtils
import 'package:flutter/material.dart';
import 'package:flutter_local_notifications/flutter_local_notifications.dart';
class Notification {
final FlutterLocalNotificationsPlugin np = FlutterLocalNotificationsPlugin();
init() async {
var android = const AndroidInitializationSettings("@mipmap/ic_launcher");
var ios = const IOSInitializationSettings();
await np.initialize(InitializationSettings(android: android, iOS: ios),
onSelectNotification: selectNotification);
}
void selectNotification(String? payload) async {
if (payload != null) {
debugPrint('notification payload: $payload');
}
}
void send(String title, String body, {int? notificationId, String? params}) {
var androidDetails = const AndroidNotificationDetails(
'channelId',
'channelName',
importance: Importance.max,
priority: Priority.high,
);
var iosDetails = const IOSNotificationDetails();
var details = NotificationDetails(android: androidDetails, iOS: iosDetails);
np.show(notificationId ?? DateTime.now().millisecondsSinceEpoch >> 10,
title, body, details,
payload: params);
}
void cleanNotification() {
np.cancelAll();
}
void cancelNotification(int id, {String? tag}) {
np.cancel(id, tag: tag);
}
}
var notification = Notification();
具体使用方式:
1、在main函数中初始化插件;
void main() async{
WidgetsFlutterBinding.ensureInitialized();
await notification.init();
runApp(const MyApp());
}
2、发送一个本地通知:
commonButton(context, "发送本地通知", onPressed: () async {
if (await Permission.notification.request().isGranted) {
debugPrint("isGranted true");
Map params = {};
params['type'] = 200;
params['id'] = "10086";
params['content'] = "content";
notification.send("title", "content", params: json.encode(params));
}else{
debugPrint("isGranted false");
final flag = await NftDialogUtils.showCommonTipsDialog(context, "请打开设置,勾选通知权限");
if(flag != null && flag){
openAppSettings();
}
}
})
3、其他api 可以在工具中进行拓展,根据业务需要,不在说明
效果截图:

点击通知输出:

打包时注意事项:GSON混淆配置
参考文章: