hi, 欢迎访问我的博客

flutter捕获应用退出弹出对话框

 

使用WillPopScope组件,它会检测到子组件的Navigation的pop事件,并拦截下来。我们需要在它的onWillPop属性中返回一个新的组件(一般是一个Dialog)处理是否真的pop该页面。

import 'dart:async';
import 'package:flutter/material.dart';

class HomePage extends StatefulWidget {
  @override
  _HomePageState createState() => _HomePageState();
}

class _HomePageState extends State<HomePage> {

    Future<bool> _onBackPressed() {
        return showDialog(
            context: context,
            builder: (context) =>
                AlertDialog(
                    title: Text('确定退出程序吗?'),
                    actions: <Widget>[
                        FlatButton(
                            child: Text('暂不'),
                            onPressed: () => Navigator.pop(context, false),
                        ),
                        FlatButton(
                            child: Text('确定'),
                            onPressed: () => Navigator.pop(context, true),
                        ),
                    ],
                ));
    }

    @override
    Widget build(BuildContext context) {
        return WillPopScope(
            onWillPop: _onBackPressed,
            child: Scaffold(
                appBar: AppBar(
                    title: Text('title'),
                ),
                body: Center(
                    child: Text('exit'),
                ),
            ),
        );
    }
}

这里有另外一种情况就是,当我们填写一些表单时,如果没填完毕就直接想要退出,这时也需要用到弹窗警告是否确定退出,这种情况form widget就直接提供了这个属性,使用方法跟上面一样;

 new Form(
       onWillPop: _onBackPressed,
       key: _formKey,
       autovalidate: true,
    child:。。。。
}

 

posted @ 2018-11-12 16:21  打静爵  阅读(6041)  评论(0编辑  收藏  举报