I have strange issue: I have StatefullWidget like this
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(...)
}
My logs looks like this:
============= 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
So from logs it looks like state of widget is rebuilt without any new route received so it is causing troubles because dispose() was called and all streams in BLoC were closed. StreamBuilder returns Scaffold in one of two states depending of stream data and in body multiple Widgets or StatelessWidgets. Nowhere is called setState(). Widget was opened by Navigator by pushRouteNamed().
My question is: What is causing such strange behaviour and how to prevent it? Idea is to create bloc each time Widget is created by pushing route (it contains contextual data, so singleton wouldn't be good)
Yes, currently they are going to fix it. Here is the flutter issue link
There is also one workaround mentioned in the link.