Flutter单击后退按钮时如何执行 [英] Flutter how to execute when clicking back button

查看:27
本文介绍了Flutter单击后退按钮时如何执行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个从底部选项卡导航调用的页面,它执行一个 initState 函数,然后我通过按钮单击导航到一个页面,该页面包含详细信息和要执行的操作,但是当我单击后退按钮转到原始页面时,initState 没有再次运行,我发现因为 Flutter 在您将一个放在顶部时不会破坏页面,因为 NAV 不在新页面上,因为它不在菜单中,如何让 initState 在单击返回时再次运行按钮还是有其他方法可以监听从后退按钮导航并运行需要更新数据的代码?

I have a page that is called from bottom tab nav which executes a initState function, I then navigate to a page via button click that has details and actions to take, however when I click the back button to goto originating page, the initState does not run again, I have found out that because Flutter does not destroy the page when you put one on top, since the NAV is not on new page as its not in the menu, how do I make initState run again on clicking back button or is there another way to listen for that navigate from back button and run the code that needs to update data?

任何帮助都会很棒.

推荐答案

你可以覆盖AppBar的默认返回箭头,然后指定你想要返回的值来触发改变Navigator.pop 被调用时的状态:

You can override the default back arrow on the AppBarand then specify the value you would like to return to trigger the change of the state when Navigator.pop is called:

伪代码

所以您需要在导航按钮的 onPressed 回调中包含类似的内容

so you need to have something like this in your onPressed callback of your navigation button

onPressed: ()async{
            var nav = await Navigator.of(context).push(newRoute);
            if(nav==true||nav==null){
              //change the state
            }
          },

在你的 newRoute 中你应该有这样的东西

and in your newRoute you should have something like this

new AppBar(
        leading: new IconButton(
          icon: new Icon(Icons.arrow_back),
          onPressed: (){Navigator.pop(context,true)}
        ),

我正在检查 nulltrue 这两个值,因为当用户点击 android 屏幕上的 BackButton(屏幕底部的那个)时会返回 null 值).我也相信 null 也将与 Flutter 中的默认 BackButton 返回,因此您实际上不需要覆盖 leading 属性,但我自己没有检查过,所以可能值得检查.

I am checking for both values null or true because the null value is returned when the user hits the BackButton on android screen (the one in the bottom of the screen). I also believe the null will also be returned with the default BackButton in Flutter so you do not actually need to override the leading property, but I have not checked that myself, so it may be worth checking.

这篇关于Flutter单击后退按钮时如何执行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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