当按下后退按钮时,应用程序会颤动关闭?

时间:2021-05-25 07:44:48

标签: flutter flutter-layout

正如标题所说,按下后退按钮后,应用程序关闭。

Container(
      margin: EdgeInsets.only(left: 20, top: 8),
      decoration: BoxDecoration(
          color: colorYellow,
          borderRadius: BorderRadius.all(Radius.circular(20))),
      height: 40,
      width: 40,
      child: IconButton(
        icon: Icon(Icons.arrow_back, color: Colors.white, size: 20),
        onPressed: () => Navigator.of(context).pop(),
      ),
    ),

3 个答案:

答案 0 :(得分:2)

使用 Navigator.pop(context); 而不是 Navigator.of(context).pop()

答案 1 :(得分:0)

  Future<bool> onBackPress(context) {
        return showDialog(
            context: context,
            builder: (context) => AlertDialog(
                  title: Text('Do you wish to exit?'),
                  actions: <Widget>[
                    TextButton(
                      child: Text('Cancel'),
                      onPressed: () => {Navigator.pop(context, false)},
                    ),
                    TextButton(
                        onPressed: () => {Navigator.pop(context, true)},
                        child: Text('Exit'))
                  ],
                ));
      }
    
    @override
      Widget build(BuildContext context) {
        return WillPopScope(
          onWillPop: () => onBackPress(context),
          child: SafeArea(),
     )};

答案 2 :(得分:0)

WillPopScope 包裹您的脚手架。每当按下后退按钮时,您都会在 onWillPop 处收到一个回调,它返回一个 Future。如果 Future 返回 true,则弹出屏幕。

 @override
 Widget build(BuildContext context) {
    return WillPopScope(
    onWillPop: () async {
        // await showDialog or Show add banners or whatever
        // return true if the route to be popped
         return false; // return false if you want to disable device back button click
       },
      child: Scaffold(),
     ),
  };

return false; 表示您的应用程序不会在点击后退按钮时关闭

相关问题