【问题标题】:How To Override the “Back” button in Flutter? [duplicate]如何覆盖 Flutter 中的“返回”按钮? [复制]
【发布时间】:2018-08-27 15:23:14
【问题描述】:

在我的主页小部件上,当用户点击系统后退按钮时,我想显示一个确认对话框,询问“您要退出应用程序吗?”

我不明白我应该如何覆盖或处理系统后退按钮。

【问题讨论】:

    标签: flutter


    【解决方案1】:

    您可以使用WillPopScope 来实现此目的。

    例子:

    import 'dart:async';
    
    import 'package:flutter/material.dart';
    
    class HomePage extends StatefulWidget {
      HomePage({Key key, this.title}) :super(key: key);
    
      final String title;
    
      @override
      State<StatefulWidget> createState() => new _HomePageState();
    }
    
    class _HomePageState extends State<HomePage> {
    
      Future<bool> _onWillPop() async {
        return (await showDialog(
          context: context,
          builder: (context) => new AlertDialog(
            title: new Text('Are you sure?'),
            content: new Text('Do you want to exit an App'),
            actions: <Widget>[
              TextButton(
                onPressed: () => Navigator.of(context).pop(false),
                child: new Text('No'),
              ),
              TextButton(
                onPressed: () => Navigator.of(context).pop(true),
                child: new Text('Yes'),
              ),
            ],
          ),
        )) ?? false;
      }
    
      @override
      Widget build(BuildContext context) {
        return new WillPopScope(
          onWillPop: _onWillPop,
          child: new Scaffold(
            appBar: new AppBar(
              title: new Text("Home Page"),
            ),
            body: new Center(
              child: new Text("Home Page"),
            ),
          ),
        );
      }
    }
    

    ??-operator 检查null,参见here。这很重要,因为如果您在对话框外单击,showDialog 会返回 null,在这种情况下会返回 false。

    希望对您有所帮助!

    【讨论】:

    • showDialog 的子级已弃用。您现在应该使用构建器。
    • 谢谢,更新了答案:)
    • 后退按钮的图标也可以改吗?
    • 是的,当然。有AppBar 占用的属性leading。您可以使用您想要的每个图标或任何其他小部件指定 IconButton
    • @SaloGala varvalue ?? false 指令告诉编译器在 varvalue 为空时返回 false
    猜你喜欢
    • 1970-01-01
    • 2021-06-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-10-10
    • 2018-02-05
    • 2021-05-02
    • 1970-01-01
    相关资源
    最近更新 更多