在Flutter中,可以使用 WillPopScope 组件来定义在用户单击 Android 设备的 Home 按钮时要执行的自定义函数。
具体实现步骤如下:
WillPopScope(
onWillPop: () async {
//定义你要执行的自定义函数
return false; // 返回 false 禁止使用 pop ,可以替代退出应用
},
child: Scaffold(
appBar: AppBar(
title: Text("保留页面"),
),
body: Container(
child: Center(
child: Text("这是要保留的页面!"),
),
),
),
);
WillPopScope(
onWillPop: () async {
_doSomething(); // 定义你要执行的自定义函数
return false; // 返回 false 禁止使用 pop ,可以替代退出应用
},
//...
);
完整示例代码如下:
class HomePage extends StatelessWidget {
@override
Widget build(BuildContext context) {
return WillPopScope(
onWillPop: () async {
_doSomething(); // 定义你要执行的自定义函数
return false; // 返回 false 禁止使用 pop ,可以替代退出应用
},
child: Scaffold(
appBar: AppBar(
title: Text("保留页面"),
),
body: Container(
child: Center(
child: Text("这是要保留的页面!"),
),
),
),
);
}
void _doSomething() {
// 定义你要执行的自定义函数
print("你点击了 Android 的 Home 键!");