dart 我如何使alertDialog在Flutter中几秒钟后自动消失?

o3imoua4  于 2023-06-19  发布在  Flutter
关注(0)|答案(4)|浏览(312)

点击按钮时将显示alertDialog,几秒钟后自动消失。在Flutter中如何做到这一点?

2eafrhcq

2eafrhcq1#

最小值例如:
5秒后关闭alertDialog

showDialog(
                      context: context,
                      builder: (context) {
                        Future.delayed(Duration(seconds: 5), () {
                          Navigator.of(context).pop(true);
                        });
                        return AlertDialog(
                          title: Text('Title'),
                        );
                      });
uurv41yg

uurv41yg2#

如果在触发Future之前关闭对话框,Future.delayed可能会导致一些问题。因此,如果您使用它,请注意showDialog不是可解除的barrierDismissible: false,并且AlertDialog没有解除它的按钮。
否则,您可以使用计时器:

Timer timer = Timer(Duration(milliseconds: 3000), (){
  Navigator.of(context, rootNavigator: true).pop();
});
showDialog(
  ... Dialog Code ...
).then((value){
  // dispose the timer in case something else has triggered the dismiss.
  timer?.cancel();
  timer = null;
});
ojsjcaue

ojsjcaue3#

您可能希望使用“SnackBar”来显示自动消失的通知。

final snackBar = SnackBar(
  content: Text('This is where you put the notice.'),
  duration: Duration(seconds: 2),
);
Scaffold.of(context).showSnackBar(snackBar);
toe95027

toe950274#

我建议使用FutureBuilder,这样当用户在超时之前关闭对话框时,这将被自动解除。

showDialog(
      context: context,
      builder: (context) {
        return FutureBuilder(
          future: Future.delayed(dismissDuration).then((value) => true),
          builder: (context, snapshot) {
            if (snapshot.hasData) {
              Navigator.of(context).pop();
            }

            return AlertDialog(
              content: Text(text),
            );
          },
        );
      },
    );

相关问题