安卓手机点击实体或者虚拟返回键,会返回上一级,当到达最上层是,点击返回退出应用,为了防止用户连续点击返回,导致应用退出,在用户点击返回到最上层时,如果再次点击返回,第一次不退出,并提升用户再次点击退出
import 'package:flutter/material.dart';
import 'package:fluttertoast/fluttertoast.dart';
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
title: '',
home: HomePage(),
);
}
}
class HomePage extends StatefulWidget {
@override
_HomePageState createState() => _HomePageState();
}
class _HomePageState extends State<HomePage> {
@override
Widget build(BuildContext context) {
return WillPopScope(
onWillPop: _onWillPop,
child: Scaffold(
appBar: AppBar(title: Text('data'),),
body: Container(
child: Center(child: Text('data')),
),
)
);
}
int last = 0;
Future<bool> _onWillPop() {
//计算两次时间间隔
int now = DateTime.now().millisecondsSinceEpoch;
if (now - last > 8000) {
last = DateTime.now().millisecondsSinceEpoch;
Fluttertoast.showToast(msg: '再次点击返回退出应用',gravity: ToastGravity.BOTTOM);
return Future.value(false);
} else {
return Future.value(true);
}
}
}