仅使用 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, when you want to refresh the HomeScreen, 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
}
}