代码之家  ›  专栏  ›  技术社区  ›  Robert

颤振单击后退按钮时如何执行

  •  18
  • Robert  · 技术社区  · 7 年前

    我有一个从底部选项卡nav调用的页面,它执行initState功能,然后我通过按钮点击导航到一个页面,该页面有详细信息和要执行的操作,但是当我点击后退按钮转到原始页面时,initState不会再次运行,我发现,因为当您将页面放在顶部时,颤振不会破坏页面,由于导航不在新页面上,因为它不在菜单中,我如何在单击后退按钮时使initState再次运行,或者是否有其他方法来侦听从后退按钮导航并运行需要更新数据的代码?

    任何帮助都会很好。

    3 回复  |  直到 4 年前
        1
  •  34
  •   novas1r1    5 年前

    你可以用 WillPopScope (创建一个小部件,该小部件注册一个回调,以否决用户试图关闭封闭的[ModalRoute]。->来自文档):

    @override
    Widget build(BuildContext context) {
     return WillPopScope(
      onWillPop: () {
        print('Backbutton pressed (device or appbar button), do whatever you want.');
    
        //trigger leaving and use own data
        Navigator.pop(context, false);
    
        //we need to return a future
        return Future.value(false);
      },
      child: Scaffold(
      ...
      ),
     );
    }
    

    希望我把你的问题答对了,这会有帮助:)!

        2
  •  24
  •   Shady Aziza    7 年前

    可以替代 AppBar 然后指定要返回以触发状态更改的值 Navigator.pop 被称为:

    伪代码

    所以你需要在你的 onPressed 回拨导航按钮

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

    在你的新路线上你应该有这样的东西

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

    我正在检查这两个值 null true 因为当用户点击android屏幕上的BackButton(屏幕底部的那个)时,会返回null值。我还相信,null也将与Flutter中的默认BackButton一起返回,因此您实际上不需要重写 leading 财产,但我自己还没有检查过,所以可能值得检查一下。

        3
  •  0
  •   adarsh    3 年前
    //if you want to perform  any operation on back button so you can use WillPopScope Widget and managed your code inside onWillpop method 
    
       
     @override
     Widget build(BuildContext context) {
            return WillPopScope( 
    
            child:Column()),
    
            onWillPop: onBackPress);
       }
            
       
    // this is onBackPress method
     Future<bool> onBackPress() {
            // your code 
       return Future.value(false);
     }