弹出第二页后触发FirstPage的setState方法

问题描述 投票:0回答:3

我在myapp中有两个页面,即FirstPage和SecondPage。

基本上,FirstPage小部件显示带有项目列表的ListView,而SecondPage小部件则是我可以向列表添加/删除项目的位置。

我可以通过以下方式导航到SecondPage:

Navigator.of(context).pushNamed("/SecondPage");

我还可以使用以下命令返回FirstPage:

Navigator.of(context).pop();

我的问题是我无法弄清楚如何在弹出SecondPage后触发FirstPage小部件的setState方法,以便更新FirstPage的ListView。

我会感激任何提示。

dart flutter
3个回答
0
投票

每当我们推动,我们将获得未来,我们可以利用未来触发setState

Future pushNamed = Navigator.of(context).pushNamed("/SecondPage");
pushNamed.then((_)=> setState(() {}));

请参阅here将数据从secondScreen发送到firstScreen。


0
投票

使用此代码将子视图中的值发送到父视图

 Widget build(BuildContext context) {
return new Scaffold(
  appBar: new AppBar(
    title: new Text(widget.title),
  ),
  body: new Center(
      child: new FlatButton(
          onPressed: () {
            Navigator.push(
              context,
              MaterialPageRoute(
                  builder: (context) => SecondView(callBackValue)),
            );
          },
          child: new Text('Open Child Widget'))),
);
}

 //Your Callback Values will be received here
void callBackValue(double value) {
print('Value $value');
}

// Your SecondPage
class SecondView extends StatefulWidget{
    final void Function(double data) callback;
    SecondView(this.callback);

    @override
    _SecondView createState() => new _SecondView();
  }

  class _SecondView extends State<SecondView>{
    @override
    Widget build(BuildContext context) {
      return new Scaffold(
        appBar: new AppBar(
          title: new Text('Child Widget'),
        ),
        body: new Center(
          child: new FlatButton(onPressed: (){
            widget.callback(10.0);
          }, child: new Text('Send Value to parent')),
        ),
      );
    }
  }

0
投票

你想要实现的是类似于Android中的startActivityForResult()方法。

这可以通过以下方式实现: -

在你的第一个活动中

  Map map = await Navigator.of(context).push(MaterialPageRoute(builder: (context) => SecondView());

// now it will wait for the secondView to return some data
//and the below code will be executed whenever the second view pops.
  setState((){});

希望这有用。

并且不要忘记在导航的方法声明中编写async

  void _navigateToSecondActivity async {
       Map map = await Navigator.of(context).push(MaterialPageRoute(builder: (context) => SecondView());
       setState((){});
  }

只需在导航到第二个活动时调用此函数即可。

或者在你的onTap()

onTap: () async{
  Map map = await Navigator.of(context).push(MaterialPageRoute(builder: (context) => SecondView());
       setState((){});
}
© www.soinside.com 2019 - 2024. All rights reserved.