如何覆盖Flutter中的"后退"按钮?

Tus*_*Pol 38 flutter

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

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

Hem*_*Raj 96

你可以用它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() {
    return 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"),
        ),
      ),
    );
  }
}
Run Code Online (Sandbox Code Playgroud)

希望它有所帮助!

  • 不推荐使用 showDialog 的子级。您现在应该使用构建器。 (5认同)
  • 是的当然。`AppBar` 具有属性 `leading`。您可以使用您想要的每个图标或任何其他小部件指定一个 `IconButton`。 (5认同)
  • 谢谢,更新了答案:) (2认同)