如何从 Flutter 中的其他 Statefull 类重建或刷新 Statefull 类?

问题描述

是否可以从另一个类重建或刷新一个类?

例如,我有一个名为“HomeScreen”的类和一个名为“SubScreen”的类。我可以通过我的底部导航栏在这个和类之间导航。

现在我在 SubScreen 类中进行了一些更改。但是当我通过底部导航栏导航回“主屏幕”时,旧值仍在“主屏幕”内。当我关闭并重新打开我的应用程序时,“主屏幕”中的所有内容都会更新。如何在不关闭我的应用程序的情况下实现“更新”?

请帮我解决这个问题,我在那里呆了差不多几个星期了......

解决方法

当您导航回该页面时,使用导航器上的 then 刷新主屏幕。我希望它能帮助你达到你的要求

而且我还需要知道您在应用程序中使用了 Provider。这意味着它更容易。

Navigator.push(
    context,MaterialPageRoute(builder: (context) => SubScreen()),).then((_){
   setState((){});
});
,

仅使用 Statefull 小部件:

  • 您可以将回调传递给第二个屏幕,并在第一个屏幕上也应更新状态时调用该回调。这种方法的缺点是它会更新整个小部件。

子屏幕

  class SubScreen extends StatefulWidget {
  final Function updateCallback;
  SubScreen({@required this.updateCallback});

  // rest of your State class  
  
  // in the State class,when you want to refresh the HomeScreen,call:
   widget.updateCallback(); // or a more safe option: widget.updateCallback?.call();
  }

class _HomeScreenState ...{
  
  //where you push the second screen
  ...
  Navigator.push(context,SubScreen(updateCallback: (){
   setState((){});
  })
  ...
}

更有效的方法: 您可以阅读有关state management approaches here
的更多信息 rxDart 示例:
为简单起见,我在主屏幕中创建主题并将主题传递给子屏幕。

子屏幕

  class SubScreen extends StatefulWidget {
  final BehaviourSubject<SomeModel> stateSubject;
  SubScreen({@required this.stateSubject});

  // rest of your State class  
   
  // in the State class,call:
   widget.stateSubject.add(newItems); //newItems is the state that you want to present on the HomeScreen too.
  // where you want to use this SomeModel state,wrap your Widget with StreamBuilder<SomeModel>,pass the widget.stateSubject as the stream,and in the builder function you can listen to changes. Example in the build just below

 Widget build(BuildContext context){
    StreamBuilder<SomeModel>(
        stream: widget.stateSubject,initialData: null,//null be default,but you can set like empty array,or anything you want
        builder: (context,snapshot) {
          var state = snapshot.data;
           // here the state contains the latest value of the subject because its a BehaviourSubject,and you will get every new state that is added to this subject.
         return Container;
        });
 }
}

主屏幕

class _HomeScreenState ...{
    final BehaviourSubject<SomeModel> stateSubject = BehaviourSubject.seeded(null); //null by default,but you can set an initial value if you need

  //where you push the second screen
  ...
  Navigator.push(context,SubScreen(stateSubject: stateSubject));
  ...

  Widget build(context){
    //here you need to wrap your widget where you want to update based on the subject
   }
}