WillPopScope 这个控件可以用来一些防止误触判断,
onWillPop
是一个回调函数,当用户点击返回按钮时被调用(包括导航返回按钮及Android物理返回按钮)。该回调需要返回一个Future
对象,如果返回的Future
最终值为false
时,则当前路由不出栈(不会返回);最终值为true
时,当前路由出栈退出。我们需要提供这个回调来决定是否退出。
#
import 'package:flutter/material.dart';
class HomePage extends StatefulWidget {
const HomePage();
@override
State<HomePage> createState() => _HomePageState();
}
class _HomePageState extends State<HomePage> {
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text("data"),
),
body: WillPopScope(
onWillPop: () async => showDialog(
context: context,
builder: (context) =>
AlertDialog(title: Text('你确定要退出吗?'), actions: <Widget>[
RaisedButton(
child: Text('退出'),
onPressed: () => Navigator.of(context).pop(true)),
RaisedButton(
child: Text('取消'),
onPressed: () => Navigator.of(context).pop(false)),
])),
child: Center(
child: ElevatedButton(
onPressed: () {},
child: Text("退出"),
),
)));
}
}