0

这个想法是,当应用程序处于前台时,我想显示一个警报对话框,当用户从对话框中按下确定按钮时,它会将它们导航到不同的屏幕。但是,alterdialog 不会出现。如果我删除警报对话框并只保留导航代码,则应用程序会在通知到达后立即导航到不同的屏幕。这是一种糟糕的用户体验,因为用户无法控制 UI。我希望用户确认他们想要导航到不同的屏幕。因此使用了警报对话框。

这是我的代码:

void initState(){ 
    super.initState();
    var initializationSettingsAndroid  = AndroidInitializationSettings('@drawable/splash');
    var initializationSettings = InitializationSettings(android:initializationSettingsAndroid);
    flutterLocalNotificationsPlugin.initialize(initializationSettings);
    
    FirebaseMessaging.onMessage.listen((RemoteMessage message) {
      print('Inside onmessage'); 
      RemoteNotification notification = message.notification;
      AndroidNotification android = message.notification?.android;
      if (notification != null && android != null) {
        flutterLocalNotificationsPlugin.show(
            notification.hashCode,
            notification.title,
            notification.body,
            NotificationDetails(
              android: AndroidNotificationDetails(
                channel.id,
                channel.name,
                channel.description,
                icon: '@drawable/splash',
                playSound: true
              ),
            ));
           
            AlertDialog(
               title:Text(notification.title),
               actions:  <Widget>[
              TextButton(
                  child: Text('Cancel'),
                  onPressed: () {
                   setState(() {
                    //Navigator.of(context).pop();
                  navigatorKey.currentState.push(
    MaterialPageRoute(builder: (_) => OrdersScreen()));
                });
                  }),

            ],
               content:SingleChildScrollView(

                 child:
                 Column(
                   crossAxisAlignment: CrossAxisAlignment.start,
                   children:[
                     Text(notification.body)
                   ]
                 )
               )
             );
      }
    });
  }
4

1 回答 1

1

您的代码只是表达了,AlertDialog但它没有做任何事情。这就是它不显示的原因。

解决方案:

您需要调用showDialog并将其传递给如下AlertDialog对象:

final AlertDialog alertDialog = AlertDialog(
        title: Text(notification.title),
        actions: <Widget>[
          TextButton(
              child: Text('Cancel'),
              onPressed: () {
                setState(() {
                  //Navigator.of(context).pop();
                  navigatorKey.currentState
                      .push(MaterialPageRoute(builder: (_) => OrdersScreen()));
                });
              }),
        ],
        content: SingleChildScrollView(
            child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [Text(notification.body)])));

showDialog(
      context: context// (or `navigatorKey.currentContext` in this case),
      builder: (BuildContext context) {
          return alertDialog;
      },
);    
于 2021-06-18T20:27:51.007 回答