如何覆盖Flutter中的“返回"按钮? [英] How To Override the “Back” button in Flutter?

查看:176
本文介绍了如何覆盖Flutter中的“返回"按钮?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

On my Home widget, when user taps system back button, I want to show a confirmation dialog asking "Do you want to exit the App?"

我不知道如何覆盖或处理系统后退按钮.

I don't understand how I should override or handle the system back button.

推荐答案

您可以使用 WillPopScope 即可实现.

You can use WillPopScope to achieve this.

示例:

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>[
          new FlatButton(
            onPressed: () => Navigator.of(context).pop(false),
            child: new Text('No'),
          ),
          new FlatButton(
            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,请参见此处.这很重要,因为如果您在对话框外单击,showDialog将返回null,在这种情况下将返回false.

The ??-operator checks for null, see here. This is important because if you click outside the dialog, showDialog returns null and in this case false is returned.

希望有帮助!

这篇关于如何覆盖Flutter中的“返回"按钮?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆