我是新手,我看到很多Android应用程序可以在双按后退按钮时退出.
第一次按下后退按钮,应用程序显示吐司"再按一次退出应用程序".以下第二次按,app退出.当然,两次印刷之间的时间必须不长.
如何在颤动中做到这一点?
And*_*sky 25
这是我的代码示例(我使用"fluttertoast"用于showong吐司 - 你可以使用小吃吧或警报或其他任何东西)
DateTime currentBackPressTime;
@override
Widget build(BuildContext context) {
return Scaffold(
...
body: WillPopScope(child: getBody(), onWillPop: onWillPop),
);
}
Future<bool> onWillPop() {
DateTime now = DateTime.now();
if (currentBackPressTime == null ||
now.difference(currentBackPressTime) > Duration(seconds: 2)) {
currentBackPressTime = now;
Fluttertoast.showToast(msg: exit_warning);
return Future.value(false);
}
return Future.value(true);
}
Run Code Online (Sandbox Code Playgroud)
您可以尝试此软件包。
在Scaffold包装所有小部件的内,放置DoubleBackToCloseApp传递的SnackBar:
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
body: DoubleBackToCloseApp(
child: Home(),
snackBar: const SnackBar(
content: Text('Tap back again to leave'),
),
),
),
);
}
}
Run Code Online (Sandbox Code Playgroud)
您也可以选择涉及的解决方案SnackBar。它不像Andrey Turkovsky的回答那么简单,但是却更加优雅,您不必依赖库。
与Key:
class _FooState extends State<Foo> {
static const snackBarDuration = Duration(seconds: 3);
final snackBar = SnackBar(
content: Text('Press back again to leave'),
duration: snackBarDuration,
);
final scaffoldKey = GlobalKey<ScaffoldState>();
DateTime backButtonPressTime;
@override
Widget build(_) {
return Scaffold(
key: scaffoldKey,
body: WillPopScope(
onWillPop: onWillPop,
child: Text('Place your child here'),
),
);
}
Future<bool> onWillPop() async {
DateTime currentTime = DateTime.now();
bool backButtonHasNotBeenPressedOrSnackBarHasBeenClosed =
backButtonPressTime == null ||
currentTime.difference(backButtonPressTime) > snackBarDuration;
if (backButtonHasNotBeenPressedOrSnackBarHasBeenClosed) {
backButtonPressTime = currentTime;
scaffoldKey.currentState.showSnackBar(snackBar);
return false;
}
return true;
}
}
Run Code Online (Sandbox Code Playgroud)
没有Key:
class _FooState extends State<Foo> {
static const snackBarDuration = Duration(seconds: 3);
final snackBar = SnackBar(
content: Text('Press back again to leave'),
duration: snackBarDuration,
);
DateTime backButtonPressTime;
@override
Widget build(_) {
return Scaffold(
body: Builder(
builder: (BuildContext context) {
// The BuildContext must be from one of the Scaffold's children.
return WillPopScope(
onWillPop: () => onWillPop(context),
child: Text('Place your child here'),
);
},
),
);
}
Future<bool> onWillPop(BuildContext context) async {
DateTime currentTime = DateTime.now();
bool backButtonHasNotBeenPressedOrSnackBarHasBeenClosed =
backButtonPressTime == null ||
currentTime.difference(backButtonPressTime) > snackBarDuration;
if (backButtonHasNotBeenPressedOrSnackBarHasBeenClosed) {
backButtonPressTime = currentTime;
Scaffold.of(context).showSnackBar(snackBar);
return false;
}
return true;
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
4352 次 |
| 最近记录: |