问题描述
我是扑扑的新手,我只是想向我的扑扑应用程序接收Firebase推送通知。当应用关闭且在后台时,将接收推送通知。但是,当应用程序打开时,接收到推送通知,但未显示警报通知(如果打开,我想在应用程序中显示推送通知标题和正文作为警报)。这是我的代码。
_fcm.configure(
onMessage: (Map<String,dynamic> message) async {
showDialog(
context: context,builder: (context) => AlertDialog(
content: ListTile(
title: Text(message['notification']['title']),subtitle: Text(message['notification']['body']),),actions: <Widget>[
FlatButton(
child: Text('Ok'),onpressed: () => Navigator.of(context).pop(),],);
print("onMessage: $message");
},onLaunch: (Map<String,dynamic> message) async {
print("onLaunch: $message");
},onResume: (Map<String,dynamic> message) async {
print("onResume: $message");
},);
有人可以帮我吗?
解决方法
当应用程序位于前景中时,当用户收到通知时,您可以使用Get包来显示SnackBar。
_fcm.configure(
onMessage: (Map<String,dynamic> message) async {
Get.snackbar("message['notification']['title']",snackPosition: SnackPosition.TOP,);
},onLaunch: (Map<String,dynamic> message) async {
print("onLaunch: $message");
},onResume: (Map<String,dynamic> message) async {
print("onResume: $message");
},);
通过'snackPosition'参数,snackBar可以显示在顶部,从而显示为警报消息。
关于如何将flutter_local_notifications软件包与FCM here结合使用,有很好的解释
, FCM为您提供三个回调。 OnResume
,OnLaunch
和OnMessage
。
当应用程序处于前台状态时,将触发onMessage
,它使您有机会执行任何自定义操作。
为了在应用程序处于前台状态时显示通知,您可以使用 Flutter Local Notifications包。
由于onMessage回调中缺少上下文,您可能无法看到警报对话框。尝试将_fcm.configure
包装在里面
SchedulerBinding.instance.addPostFrameCallback((_){ [_fcm.configure block] });
,
最后,我可以使用 overlay_support 软件包
来解决我的问题我已提及以下问题链接:
Flutter - Firebase Messaging Snackbar not showing
Flutter - how to get current context?
我按照下面的教程和程序包解决了问题
教程:https://medium.com/flutter-community/in-app-notifications-in-flutter-9c1e92ea10b3
软件包:https://pub.dev/packages/overlay_support/install
我将MaterialApp()小部件包装在OverlaySupport()小部件中。然后将showOverlayNotification添加到_fcm.configure-> onMessage:
_fcm.configure(
onMessage: (Map<String,dynamic> message) async {
print("onMessage: $message");
showOverlayNotification((context) {
return Card(
margin: const EdgeInsets.symmetric(horizontal: 4),child: SafeArea(
child: ListTile(
leading: SizedBox.fromSize(
size: const Size(40,40),child: ClipOval(
child: Container(
color: Colors.black,))),title: Text(message['notification']['title']),subtitle: Text(message['notification']['body']),trailing: IconButton(
icon: Icon(Icons.close),onPressed: () {
OverlaySupportEntry.of(context).dismiss();
}),),);
},duration: Duration(milliseconds: 4000));
print(message['notification']['title']);
},dynamic> message) async {
print("onLaunch: $message");
},dynamic> message) async {
print("onResume: $message");
},);