我有一个奇怪的问题:我有这样的 StatefullWidget
class ActionDetailView extends StatefulWidget {
static const routeName = '/actionDetails';
@override
_ActionDetailViewState createState() {
print("Create state");
return _ActionDetailViewState();
}
}
class _ActionDetailViewState extends State<ActionDetailView>
with WidgetsBindingObserver {
ActionDetailBloc _bloc = ActionDetailBloc();
_ActionDetailViewState() {
print("ActionDetailViewState constructed");
}
@override
void didChangeDependencies() {
print("DidChangeDependencicse");
final String actionUID = ModalRoute.of(context).settings.arguments;
_bloc.init(actionUID);
super.didChangeDependencies();
}
@override
Widget build(BuildContext context) {
return StreamBuilder(...)
}
我的日志如下所示:
============= Enter to view first time =======
2020-01-08 09:53:36.760 5960-5987/ I/flutter: View action //pushed route from another place in code
2020-01-08 09:53:36.808 5960-5987/ I/flutter: Create state //constructor of State is called
2020-01-08 09:53:36.810 5960-5987/ I/flutter: ActionDetailViewState constructed //confirmation of above
2020-01-08 09:53:36.811 5960-5987/ I/flutter: DidChangeDependencicse
2020-01-08 09:53:36.812 5960-5987/ I/flutter: init actionDetailBloc //bloc init method for fill streams
2020-01-08 09:53:36.864 5960-5987/ I/flutter: LoadingUsers //loading state
2020-01-08 09:53:38.253 5960-5987/ I/flutter: pushing to stream
2020-01-08 09:53:38.276 5960-5987/ I/flutter: ReceivedList //data received
=============== Back pressed ====
2020-01-08 09:53:40.870 5960-5987/ I/flutter: DidChangeDependencicse //suddenly it is rebuilt despite not visible
2020-01-08 09:53:40.870 5960-5987/ I/flutter: init actionDetailBloc
2020-01-08 09:53:40.884 5960-5987/ I/flutter: ReceivedList
2020-01-08 09:53:42.160 5960-5987/ I/flutter: pushing to stream
因此,从日志来看,小部件的状态似乎是在没有收到任何新路由的情况下重建的,因此它会造成麻烦,因为调用了 dispose() 并且 BLoC 中的所有流都已关闭。StreamBuilder 根据流数据和主体中的多个 Widget 或 StatelessWidget 以两种状态之一返回 Scaffold。无处被称为 setState()。Navigator 通过 pushRouteNamed() 打开了小部件。
我的问题是:是什么导致了这种奇怪的行为以及如何防止它?想法是每次通过推送路由创建 Widget 时创建 bloc (它包含上下文数据,所以单例不会好)