Rah*_*ahi 4 android dialog push-notification dart flutter
当推送通知到达我的应用程序时,我试图在任何活动屏幕中显示一个对话框。在应用程序运行时。我可以通过用户交互显示对话框,例如单击按钮。但我想在没有用户交互的情况下展示它。如果有通知到达,则仅应触发对话框。我试图用后台获取来调用它。但找不到任何解决方案。因此,请提前帮助并感谢您。
我以前遇到过同样的问题,我会展示我的解决方案,希望它适合你
解决方案的主要内容:当应用程序像 HomePage 一样生活时,我们的页面不会从导航器堆栈中弹出,因此我们可以使用此页面中的 BuildContext
因此,通过将 必须仍在 Navigator 堆栈中的 StatefulWidget(如主页)的上下文(在应用程序处于活动状态时不弹出它)传递给处理通知数据的类,您可以使用它来显示对话框
现在让我们写一些代码:
例如,我们有NotificationManger类,此类用于使用静态方法处理通知消息
class NotificationManger {
static BuildContext _context;
static init({@required BuildContext context}) {
_context = context;
}
//this method used when notification come and app is closed or in background and
// user click on it, i will left it empty for you
static handleDataMsg(Map<String, dynamic> data){
}
//this our method called when notification come and app is foreground
static handleNotificationMsg(Map<String, dynamic> message) {
debugPrint("from mangger $message");
final dynamic data = message['data'];
//as ex we have some data json for every notification to know how to handle that
//let say showDialog here so fire some action
if (data.containsKey('showDialog')) {
// Handle data message with dialog
_showDialog(data);
}
}
static _showDialog({@required Map<String, dynamic> data}) {
//you can use data map also to know what must show in MyDialog
showDialog(context: _context,builder: (_) =>MyDialog());
}
}
Run Code Online (Sandbox Code Playgroud)
现在我们 在我的应用程序的FCM类中将此回调作为顶级或静态(必须是其中之一)
class Fcm {
static final FirebaseMessaging _fcm = FirebaseMessaging();
static initConfigure() {
if (Platform.isIOS) _iosPermission();
_fcm.requestNotificationPermissions();
_fcm.autoInitEnabled();
_fcm.configure(
onMessage: (Map<String, dynamic> message) async =>
NotificationManger.handleNotificationMsg(message),
onLaunch: (Map<String, dynamic> message) async =>
NotificationManger.handleDataMsg(message['data']),
onResume: (Map<String, dynamic> message) async =>
NotificationManger.handleDataMsg(message['data']),
onBackgroundMessage: async =>
NotificationManger.handleDataMsg(message['data']);
}
static _iosPermission() {
_fcm.requestNotificationPermissions(
IosNotificationSettings(sound: true, badge: true, alert: true));
_fcm.onIosSettingsRegistered.listen((IosNotificationSettings settings) {
print("Settings registered: $settings");
});
}
}
Run Code Online (Sandbox Code Playgroud)
要了解有关回调 fcm 的更多信息,请阅读此内容
好的,现在在我们的HomePage State 中,在initState方法中初始化我们的类
@override
void initState() {
super.initState();
Future.delayed(Duration.zero,(){
///init Notification Manger
NotificationManger.init(context: context);
///init FCM Configure
Fcm.initConfigure();
});
}
Run Code Online (Sandbox Code Playgroud)
如前所述,当应用程序显示时主页不会弹出,您可以启动另一个页面但不关闭主页
我希望这有帮助
| 归档时间: |
|
| 查看次数: |
1998 次 |
| 最近记录: |