Riz*_*wan 16 android dart flutter
有什么方法可以onBackPressed从Android后退按钮捕获事件吗?
我尝试了WillPopScope但是我的onWillPop功能仅在我点击材料后退箭头按钮时触发
我这样说:
class MyView extends StatelessWidget{
Widget build(BuildContext context) {
return new WillPopScope(
onWillPop: () async {
debugPrint("Will pop");
return true;
},
child: ScopedModel<AppModel>(
model: new AppModel(),
child: new Scaffold(......
Run Code Online (Sandbox Code Playgroud)
我需要抓住它,因为不知何故我的屏幕在按下后退按钮时表现不正确,它弹出屏幕和它下面的屏幕,但不知何故,使用材料后退箭头按钮工作正常.
更新:
the code works, my problem was not in the pop of this screen, but on the previous screen, I use 2 MaterialApp widgets, and somehow it gave a weird behavior.
Run Code Online (Sandbox Code Playgroud)
Arn*_*rge 25
为了防止导航,WillPopScope是正确的方法,应该按如下方式使用:
class Page2Route extends MaterialPageRoute {
Page2Route() : super(builder: (context) => new Page2());
}
class Page2 extends StatelessWidget {
@override
Widget build(BuildContext context) {
return new WillPopScope(
child: new Scaffold(
appBar: new AppBar(
title: new Text('Page 2'),
),
body: new Center(
child: new Text('PAGE 2'),
),
),
onWillPop: () {
return new Future(() => false);
},
);
}
}
Run Code Online (Sandbox Code Playgroud)
可以像这样调用页面:
Navigator.of(context).push(new Page2Route());
Run Code Online (Sandbox Code Playgroud)
不要使用以下方法进行导航,因为它与最新的Flutter有一些问题:
Navigator.push(context, new Page2Route());
Run Code Online (Sandbox Code Playgroud)
Thi*_*chi 19
使用WillPopScope方法并返回false
@override
Widget build(BuildContext context) {
return WillPopScope(
onWillPop: () async {
// Do something here
print("After clicking the Android Back Button");
return false;
},
child: Scaffold(
appBar: AppBar(
title: Text("Handling the back button"),
),
body: Center(
child: Text("Body"),
),
),
);
}
Run Code Online (Sandbox Code Playgroud)
Mit*_*tch 15
这应该是有帮助的。
@override
Widget build(BuildContext context) {
return WillPopScope(
onWillPop: () {
_moveToScreen2(context, );
},
child: Scaffold(
key: _scaffoldKey,
appBar: AppBar(
leading: IconButton(
icon: Icon(Icons.arrow_back),
onPressed: () {
_moveToScreen2(context);
}),
title: Text("Screen 1"),
),
),
);
}
/**
* This is probably too thin to be in its own method - consider using
* `Navigator.pushReplacementNamed(context, "screen2")` directly
*/
void _moveToScreen2(BuildContext context) =>
Navigator.pushReplacementNamed(context, "screen2");
Run Code Online (Sandbox Code Playgroud)
它检测硬件后退按钮,并且在使用 persist_bottom_nav_bar 的情况下特别有用
@override
void initState() {
super.initState();
BackButtonInterceptor.add(myInterceptor);
}
@override
void dispose() {
BackButtonInterceptor.remove(myInterceptor);
super.dispose();
}
bool myInterceptor(bool stopDefaultButtonEvent, RouteInfo info) {
print("BACK BUTTON!"); // Do some stuff.
return false;// return true if u want to stop back
}
Run Code Online (Sandbox Code Playgroud)
只是在这里添加一个重要的观点。请注意,通过使用WillPopScope,我们将失去 iOS 上的向后滑动手势。
参考: https: //github.com/flutter/flutter/issues/14203
| 归档时间: |
|
| 查看次数: |
15714 次 |
| 最近记录: |