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

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

推荐答案

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

??-operatornull,见here.这一点很重要,因为如果在对话框外部单击,showDialog将返回null,在本例中将返回false.

希望有帮助!

Flutter相关问答推荐

如何在容器小部件中的图像旁边添加文本?

BoxConstraints强制使用无限宽度(列中的Listview)

Flutter 渲染HTML和数学(LaTeX和Katex)

如何将小部件代码移动到另一个文件以获得更好的可读性

将自定义容器附加到屏幕底部

Flutter Dismissible 不会在 startToEnd 滑动时被关闭

网页浏览器不支持鼠标滚动的行项目

在我使用 flutter_riverpod stateprovider 重新保存代码之前,UI 主题状态不会更新

Flutter Firebase 升级后出现问题? ARC 语义问题 (Xcode): Select 器appleCredentialWithIDToken:rawNonce:fullName:没有已知的类方法

为什么我们使用 RiverpodGenerator

Flutter ListView 在 Column 中工作但在 Row 中不工作

如何将 chrome web 模拟器添加到 vs code

访问 AsyncSnapshot 中的嵌套属性

SfCircularChart 周围的额外间距

如何在 Flutter 中使用简写 IF 禁用单选按钮?

.info/connected 这两个代码之间有什么区别吗?

如何修复int类型不是String类型的子类型

使用 onPressed 切换到另一个屏幕无法正常工作

如何在 ListView.builder 中扩展文本?

我想在数组中添加项目