在Flutter上捕获Android后退按钮事件 [英] catch Android back button event on Flutter

查看:661
本文介绍了在Flutter上捕获Android后退按钮事件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我可以通过Android后退按钮捕获onBackPressed事件吗?

Is there any way I can catch the onBackPressed event from Android back button?

我已经尝试过WillPopScope,但是我的onWillPop函数仅在我点击材质"后退箭头按钮时触发

I've tried the WillPopScope but my onWillPop function only triggered when I tap on the Material back arrow button

我这样说:

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(......

我需要捕获它,因为按下返回按钮时,我的屏幕以某种方式表现不正确,会弹出屏幕及其下方的屏幕,但是以某种方式,使用实质性的返回箭头按钮是正常的.

I need to catch it because somehow my screen behaved incorrectly when it came to back button pressed, it pops the screen and the screen below it, but somehow, using material back arrow button works normal.

更新:

代码有效,我的问题不在该屏幕的弹出窗口中,而是在前一个屏幕上,我使用了2个MaterialApp小部件,并且以某种方式产生了怪异的行为.

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.

推荐答案

为了防止向后导航 WillPopScope 是正确的方法,应按以下方式使用:

In order to prevent navigating back WillPopScope is the correct way and should be used as follow:

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: () async {
        return false;
      },
    );
  }
}

Future<T> pushPage<T>(BuildContext context, Widget page) {
  return Navigator.of(context)
      .push<T>(MaterialPageRoute(builder: (context) => page));
}

可以像这样调用页面:

pushPage(context, Page2());

这篇关于在Flutter上捕获Android后退按钮事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆