这些是完成以下步骤的步骤
- 在不打扰用户的情况下接收通知(在系统托盘中没有任何警报的静默方式)
- 让 localNotification Pkg 启动进度通知
- 执行后台任务并完成后
- 通过 LocalNotifications Pkg 取消通知
确保您的 .yaml 文件中包含以下内容...在解决此问题时,我有以下版本:
firebase_messaging: ^11.1.0
firebase_core: ^1.10.0
flutter_local_notifications: ^9.1.
对于本地通知包,让我们创建一个类来使用它的服务
import 'package:firebase_messaging/firebase_messaging.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter_local_notifications/flutter_local_notifications.dart';
class LocalNotificationService {
static final FlutterLocalNotificationsPlugin _notificationsPlugin = FlutterLocalNotificationsPlugin();
static void initialize(BuildContext context) {
final InitializationSettings initializationSettings = InitializationSettings(
android: const AndroidInitializationSettings("@mipmap/your_icon"));
_notificationsPlugin.initialize(initializationSettings);
}
//=================================================
//==============this is the update notification
static Future<void> showProgressNotification() async {
const int maxProgress = 5;
for (int i = 0; i <= maxProgress; i++) {
await Future<void>.delayed(const Duration(seconds: 1), () async {
final AndroidNotificationDetails androidPlatformChannelSpecifics =
AndroidNotificationDetails('progress channel', 'progress channel',
channelDescription: 'progress channel description',
channelShowBadge: false,
importance: Importance.max,
priority: Priority.high,
playSound: false,
showProgress: true,
maxProgress: maxProgress,
progress: i);
final NotificationDetails platformChannelSpecifics =
NotificationDetails(android: androidPlatformChannelSpecifics);
await _notificationsPlugin.show(
0,//I use this id to cancel it from below method
'progress notification title',
'progress notification body',
platformChannelSpecifics,
payload: 'item x');
});
}
}
//=========================and this is for the ProgressNotification to be cancelled
static Future<void> cancelNotification() async {
await _notificationsPlugin.cancel(0);
}
}//end of class
让你在你的Widget的init方法中初始化它
@override
void initState() {
// TODO: implement initState
super.initState();
LocalNotificationService.initialize(context);
}
最后...这是您的 Main() 和顶级处理程序的外观
//Receive message when app is in background/minimized
//THIS IS THE TOP LEVEL HANDLER.. as it is outside the scope of main()
Future<void> backgroundHandler(RemoteMessage message) async{
print("from the Background Handler Top Function()..............");
print(message.data.toString());
//now for the localNotification to take over
await LocalNotificationService.showProgressNotification();
await Future<void>.delayed(const Duration(seconds: 2));//faking task delay
await LocalNotificationService.cancelNotification();//by default I have made id=0
}
void main() async{
WidgetsFlutterBinding.ensureInitialized();
await Firebase.initializeApp();
FirebaseMessaging.onBackgroundMessage(backgroundHandler);//this has to be a TOP LEVEL METHOD
runApp(MyApp());
}
在服务器端发送通知时确保只有数据{}...见@Junsu Cho 回答