I've got an app in Flutter that's pulling a lot of data in the parent screen. The parent screen gets divided into a few child screens and those go to a few more child screens.
Now, in order to make sure this isn't pulling data all the time from the API, I'm only pulling it once in the root screen - which is fine 90% of the time.
All the subsequent updates are broadcasted throughout the app via firebase cloud messaging
If I'm on screen 3, I need to update data in screen 1 which should also update data which will eventually be displayed on screen 2. I'm currently using this method to pass my data around (https://flutter.io/cookbook/navigation/passing-data/)
For example, screen 1 contains three projects. Each project has its own screen.
Screen 2.1 is for project 1, screen 2.2 is for project 2 and so on.
In screen 2.1, there are n to do lists.
Now if I open the to do list, I reach screen 3 with the data of the first to do list of project 1.
In a firebase cloud messaging data notification, I receive the new information of this todo list and something from the todo list of project 2 todo list 1.
How do I maintain consistency and update the data across the board?
Do I need to change my architecture and use Redux or something along those lines?
Very good question!
You will need a central "data service" that acts as a single source of truth.
It loads the initial data and stores it inside of it, it also updates the data when a cloud message arrives, and notifies all widgets that depend on the data that the data has changed.
The screens never store a mutable copy of the data, instead they query the data service to get the latest data.
Depending on the complexity of your app, there are different solutions which work either with or without streams.
InheritedWidget
is a basic solution Flutter comes with. You would usually have aStatefulWidget
with aState
that wraps yourMaterialApp
with anInheritedWidget
to broadcast theState
to your screens.scoped_model is thin wrapper around
InheritedWidget
, but basically offers the same feature. Again, the model provider must wrap yourMaterialApp
to make it available on all screens.BLoC and flutter_redux are more advanced solutions.
This question is actually related to maintaining state across app. Flutter supports various methods for maintaining state. It depends on what you are building.
Inherited Widget: It is the simplest way but it have drawbacks when state has to maintained deeep into widget tree.
Scoped Model: This package is useful for maintaining state across its descendants.
Streams(BLoC): It is the best way to maintain state across the app. Flutter uses similar process for maintaining state in app widget tree. In flutter everything is essentially a stream.
More resources for BLoC implementations. Flutter Show BloC Pattern implementation