- WillPopScope
- addScopedWillPopCallback 启用此路由以使用户否决尝试以将其关闭。
典型应用是如果用户尝试退出表单,则警告用户有关未保存的表单数据。连按两次返回键退出APP。
工作示例
import 'dart:async';
import 'package:flutter/material.dart';
import 'package:toast/toast.dart';
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
initialRoute: '/',
routes: {
'/': (context) => HomePage(),
},
);
}
}
class HomePage extends StatefulWidget {
@override
_HomePageState createState() => _HomePageState();
}
class _HomePageState extends State<HomePage> {
Timer _closeTimer;
@override
Widget build(BuildContext context) {
return WillPopScope(
onWillPop: () async {
if (_closeTimer?.isActive ?? false) {
return true;
}
Toast.show(
"再次点击退出app",
context,
duration: Toast.LENGTH_SHORT,
gravity: Toast.BOTTOM,
);
_closeTimer = Timer(Duration(milliseconds: 1000), null);
return false;
},
child: Scaffold(
appBar: AppBar(
title: Text('Home Page'),
),
body: Center(
child: Text('home page'),
),
),
);
}
}