我是Flutter开发的新手。谁能和我分享如何在颤振中禁用后按。
在Android中,我们可以使用onbackpressed方法。
@Override
public void onBackPressed() {
// super.onBackPressed(); commented this line in order to disable back press
//Write your code here
Toast.makeText(getApplicationContext(), "Back press disabled!", Toast.LENGTH_SHORT).show();
}
扑朔迷离怎么办?
答案 0 :(得分:4)
将小部件包装在WillPopScope
内,并在Future
属性中返回错误的onWillPop
@override
Widget build(BuildContext context) {
return WillPopScope(
onWillPop: () => Future.value(false),
child: Scaffold(
appBar: AppBar(
title: const Text("Home Page"),
),
body: Center(
child: const Text("Home Page"),
),
),
);
}
请参阅此文档:https://docs.flutter.io/flutter/widgets/WillPopScope-class.html
答案 1 :(得分:1)
最简单的方法是使用WillPopScope
,但是如果出于某些原因您不想或不能使用WillPopScope
小部件,这是另一种方法。
class MyWidget extends StatefulWidget {
@override
_MyWidgetState createState() => _MyWidgetState();
}
class _MyWidgetState extends State<MyWidget> {
ModalRoute<dynamic> _route;
@override
void didChangeDependencies() {
super.didChangeDependencies();
_route?.removeScopedWillPopCallback(_onWillPop);
_route = ModalRoute.of(context);
_route?.addScopedWillPopCallback(_onWillPop);
}
@override
void dispose() {
_route?.removeScopedWillPopCallback(_onWillPop);
super.dispose();
}
Future<bool> _onWillPop() => Future.value(false);
@override
Widget build(BuildContext context) => Container();
}