Open syfulin opened 4 years ago
It is not the right approach, and is here to demonstrate a point.
This code was thrown together as part of a presentation to a Flutter study group, and had roughly these goals:
Show that we can use a cubit to manage the state of the entire app. This is demonstrated by the LoginCubit being put on the top of the tree of the CubitApp.
Show that we can use cubits to manage the state of routes. This is demonstrated by putting an OverviewCubit on top of the MainRoute.
Show that we can use cubits to manage the state of other parts of the tree. This is demonstrated in two ways:
By creating a LocationVisibilityCubit on the CameraDetails widget to show that we can use a simple cubit to manage the state of widgets on separate branches of the tree -- in this case I use it for both LocationToggle and CameraList widgets, and it is simply a cubit that keeps the state of the UI.
By (clumsily) creating a CameraCubit for each item of the list view in CameraList. Now, we need to pass the repository to this cubit, and this is where things get interesting.
The flutter_bloc package gives us a RepositoryProvider widget that can be used to make a repository available to different parts of the tree. I added one to the top of the MainRoute, and used it to create the different CameraCubit on the ListView. But by doing this, I'm opening way for anyone on the tree to use the repository directly. So here I wanted to demonstrate why you should NOT use a RepositoryProvider -- unless, of course, you have a strong reason to, which, again, isn't the case here.
The code you pointed to is exactly that. See how just below that I have the right disconnection through the LoginCubit. At this point of the presentation we would have a discussion on how we would create the CameraCubits without making the repository available to the entire tree (I do have at least a couple of good ideas, but I didn't test them to see which would work better).
And now the presentation would shift focus to this new disconnected state that was not reported to the app -- so this code directly calling the repository is then used to pretend we were disconnected by the hypothetical server.
As each cubit has their own responsibility, neither the CameraCubit nor the OverviewCubit have to care if we're connected or not, so when the repository throws and UnauthorizedError, we catch it as high as possible on the tree and call the LoginCubit to disconnect, thus changing the state of the entire app. There are different ways to achieve this, and here I would steer the discussion to give a brief introduction on the use of Zones.
It turns out that in this example in the file https://github.com/arctouch-rafaelsouza/flutter-study-cubit/blob/complete/lib/routes/main_route.dart on line 61 there is a call from the UI to Data directly, not via BLoC? Is this the right approach?
onPressed: RepositoryProvider.of<BogusRepository>(context).logout