我是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();
}
在颤动怎么可能呢?
将您的小部件包裹在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
最简单的方法是使用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();
}