How to handle communication between Blocs - flutter

I'm working with the flutter_bloc library. Imagine the situation, that you are navigating deep in your app and every screen on the navigationstack presents data (slightly differnet because otherwise it wouldn't make sense), that can be modified by the user. Because we are using Bloc, every screen is connected to it's own bloc. Now, the user modifies the data.
My question: How can I tell the other Blocs/screens to rebuild with the updated data?
To my understanding, the blocs on the routes which I'm not currently viewing, get closed. So they don't listen to events anymore.
EDIT: This assumption is wrong, see answer.

Final answer. My assumption was wrong. Blocs don't get closed, if the route is still on the navigation stack. So you can still add events to Blocs, which are on other routes.

Related

Best way to architect a BLoC app in Flutter

My app requires to consume different attributes of a User object in different sections of the app i.e. different screens and dialogs.
Example of User attributes would be a list of followers and following.
I need this User object to be reactive, i.e. should append a new user (response from api call) to it's following list when the subsequent action is performed.
Currently I plan to use certain BLoC's as Reactive View Models (from MVVM) for each screen (so that the business logic is separated from the presentation layer) and have a global User BLoC listening to these View Models.
For example :- User BLoC can listen to local View Model BLoC for follow user page and when the view model emits a successful state the response can be added to the User BLoC's User state's following list.
How feasible and performant would an implementation like this be? Is this the standard way of doing things in BLoC. I looked around for examples like these but could only find simple implementations of BLoC architecture. Would this be too over kill for a mid sized app?
Much appreciated!

Flutter - multi cubit/bloc architectural design pattern

What's the best approach to make something like parent-children bloc architecture? Very often I face a problem when there is a need to establish communication between cubits or blocs.
Let's image a form where we would like to create a new user:
User name
User role (separate cubit, fetch all possible option from API)
Calendar (separate cubit, a lot of calculations made)
Apply button (main BLoC which is responsible to save new user). First
approach:
We need to get each cubit's state and emit new state when clicking on Apply button.
First approach:
var role = context.read<RolesCubit>().state as RoleSelected;
var date = context.read<CalendarCubit>().state as DateSelected;
context.read<CreateUserBloc>.add(CreateNewUserEvent((role: role, date: date));
Pros:
good granulation,
each small cubit is responsible for one thing eg getting a list of available roles and choose one
easier to maintain tests,
cubits can be reused in many places
Cons:
a need to remember to update in each place where main CreateNewUserEvent is added (imagine we would like to add 3rd sub cubit responsible for Access or Salary).
need to know each sub-cubit's state before we add "main" event. I should copy this logic to other places where this event is added. Maybe another example: I wanted to follow this approach with paginated list, on scroll refresh indicator action and one of sub page, therefore I had to check each sub-cubit state and after that I could add main event CreateNewUserEvent;
Second approach:
context.read<CreateUserBloc>.add(DateChanged((newDate));
context.read<CreateUserBloc>.add(RoleChanged((newRole));
context.read<CreateUserBloc>.add(CreateNewUserEvent(());
Create one big BLoC which can do all responsibilities.
Pros:
everything is kept in one place. When we select new role or new date,
"master" BLoC is immediately informed about change and decides what
to do next.
Cons:
big piece of code which is hard do maintain and test smaller parts
can not be reused in other places because it's monolith
Third approach
Stream subscription and make "master" bloc strictly dependent of sub-cubits. Master's cubit constructor requires a stream of sub-cubits. Explained here:
I hope I explained a problem in a simple way. Whats the best approach to maintain complex architectural design in flutter?

Can i call cubit from another cubit?

i'm working on an application that uses cubits, to manage the state.
Very often when i need to make an api request i need to get my current localization (handle possible exceptions) and then send it to backend. So i guess i should use cubit for the requests and for getting my current localization.
So now my question is how should i handle that? Can i somehow call gpsLocalizationCubit from another cubit? Should i call gpsLocalizationCubit and on success call requestCubit with the use of bloc listener? But then how should i manage loading screen that should be visible for both getting localization and api request?
Another problem is that i have multiple similiar request (that need to use current localization) in single view.
Thanks for the answers :D

Flutter is using provider to load data is the right option?

So i have a situation where i make an request from the server for one widget.
The widget is at the home page, lets take the worst case where the data is huge and the request take time.
Should i change the widget to stateless and make a provider which i will initialize before i run the app with all the initial data?
Should i contain all the data of the widgets at home page and deliver theme as props, i miss understood the concept of managing the state here, I'm coming from vue and i try to write my first app and I'm struggling how to structure my data through the routes.
I would like if some one explain or give a good source that show how to initialize data from third party
before the home page reload.
Which approach is better getting all the app data before the app reload or request data every time from db with cash
You might have seen this approach in other apps as well which is to show a splash screen until the data has been loaded and ready to be shown. This approach is mostly used by apps which got large data to load at the start. You could achieve this in your initState like the following.
#override
void initState() {
loadData();
splashTimer = Timer(Duration(seconds: 4), () {
_goToHome();
});
super.initState();
}
State management in flutter is a topic with hot debate, there is no best approach, but using one for sure is better than nothing. However there are exceptions to this, sometime adding a state management to a simple part of the app is not recommended. Regarding your case, it can be done without a full state management solution, by using a FutureBuilder for example. Or it can be also done with Provider, BloC, Redux...
As a naïve general rule, if the state is to be passed down the widget tree more than 1 or 2 levels, you should probably start looking for a state management solution depending on the use case. As I already have said, there is no one best state management solution.
Also, it is ok to use more than one as long as you know what you are doing but in general as a best practice it is not recommended to use more than one.
Regarding the second part of the question, it totally depends on the nature of the data and it's size. If the data is big and it is a small possibility that the user will be using all of it, it is better to load it on demand, also loading all the data upfront will increase the cost on the backend side.
However getting the data upfront, makes the experience more seamless to the user (Not waiting while using the app, but he will have to wait a little extra when the app is first loading).
So as you see it is a balance. Also it is good for the server and the app to do some type of caching since it helps reduce the work on the server side and decrease the bandwidth usage on the phone.
An example for caching images you can use Cached Network Image Link, example from flutter cookbook Link.

Is a Stream<List<Object>> from Firebase snapshot returning the entire node at every change in the node? Flutter

I'm starting learning Flutter as I want to port my iOS app to Flutter to also run on Android.
I use Firebase real time database for the back-end and I saw that the firebase_database package should suit my needs, allowing me to use the db I already have.
I'm also learning to use the BLoC pattern but all the bloc tutorials I found are for Firestore and all the Event/State/Bloc/Repository/Streaming is still quite confusing to me right now.
What should be the right implementation of the bloc pattern?
To a basic level I do understand it and I like it very much, but thinking of a way to implement it for my needs is resulting a bit overwhelming.
Following this diagram the 6 connections data flow should be:
(UI -> BLoC) An event will be sent to the bloc.
(BLoC -> Repository) The Bloc maps the event to a Repository method.
(Repository -> Database) The Repository methods are database Create/Update/Delete methods.
(Database -> Repository) The Repository database Read method gets database Data.
(Repository -> BLoC) The return from Repository database Read method takes the Data into BLoC.
(BLoC -> UI) The BlocProvider uses the Data to rebuild the UI.
Now what I'm not sure I figured out is the data going back to the UI.
At step 2 if I map the event to a method that returns the data as a Stream<List<Object>> then via a BlocProvider at step 6 the UI(stateless widget) gets rebuilt accordingly.
Now, as I see it, that would be a lot of unnecessary repeating data downloads if for any change, the whole node gets downloaded, also Google's bills you on downloads.
In the Firebase iOS SDK you can attach observers to a node, so you just get a snapshot with the .childAdded/.childRomovedetc etc, and use it to modify your UI.
To avoid useless downloads and keep my account safe, I'd rather make a query on a node with the keepSynced bool set to true ( https://pub.dev/documentation/firebase_database/latest/firebase_database/Query-class.html ). This should (as the iOS SDK) return at first firing, a snapshot with the whole node and than snapshots with just new/updated/delete when something changes right?
To implement this way instead, should I use a List<Object> that I update manually when getting the snapshot and a stateful widget? This is actually how my iOS app works at the moment.
Thank you very much for the help and sorry for the long question, making the switch from Swift is taking it's time.
Firebase listeners only transfer the minimal amount of data that actually changed at the node being listened to. It does NOT transfer the entire node and all of its children each time anything changes. So, it's not as expensive as you're imagining it to be.