使用WillPopScope組件,它會檢測到子組件的Navigation的pop事件,並攔截下來。咱們須要在它的onWillPop屬性中返回一個新的組件(通常是一個Dialog)處理是否真的pop該頁面。app
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就直接提供了這個屬性,使用方法跟上面同樣;async
new Form( onWillPop: _onBackPressed, key: _formKey, autovalidate: true,
child:。。。。
}