如何在Flutter中覆盖“返回”按钮?

174

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

我不明白如何覆盖或处理系统返回按钮。

1个回答

364
你可以使用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"),
        ),
      ),
    );
  }
}

?? 运算符用于检查 null,请参见这里。这很重要,因为如果您在对话框外单击,showDialog 将返回 null,此时将返回 false。


5
showDialog的子组件已经过时了,现在应该使用builder。 - Bostrot
7
谢谢,已更新回答 :) - Hemanth Raj
5
当然可以。AppBar 有一个 leading 属性,您可以指定一个 IconButton 并使用您想要的任何图标或其他任何小部件。 - Hemanth Raj
1
抱歉,我认为它是可以的。你的意思是它只能与Flutter返回按钮一起使用吗?我发现它也可以与实体和虚拟返回按钮一起使用。 - Hemanth Raj
1
@SaloGala varvalue ?? false 指令告诉编译器,如果 varvalue 为 null,则返回 false。 - Steve
显示剩余8条评论

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接