[AsKai] Flutter captures user exiting app pop-up prompt

Flutter captures the user exiting the app pop-up prompt

Using the WillPopScope component, it will detect the navigation pop event of the child component and intercept it. We need to return a new component (usually a Dialog) in its onWillPop property to handle whether the page is really popped.

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'),
                ),
            ),
        );
    }
}

There is another situation here. When we fill in some forms, if we don’t complete the filling, we want to exit directly. At this time, we also need to use the pop-up window to warn whether we are sure to exit. In this case, the form widget directly provides this attribute. The method of use is the same as above;

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

}

Reference original text:

Portal

Guess you like

Origin blog.csdn.net/qq_42362997/article/details/111471592