'Best way to trigger viewModel reload in Stacked Architecture
I am using the Stacked architecture in a Flutter app.
I have two views - ScoresPage and NewScorePage, each with their own ViewModel. Scores are stored in the database locally but also sent to an API.
ScoresPage displays all scores and NewScorePage collects information and asks its ViewModel to create a new score.
I go from the ScoresPage via a Navigator.push call to NewScorePage and use Navigator.pop to come back to ScoresPage.
I would like to refresh the ScoresPage when a new score is added once the NewScorePage is poped. What is the best way of doing this?
Solution 1:[1]
you can check out this page https://pub.dev/packages/stacked to rebuild your UI with the new updated ViewModel state was mentioned there
Solution 2:[2]
You can return data from NewScoresPage to the ScoresPage with Navigator.pop, read this example. Also check if the returned data is null, because user can go back without creating new result. After getting the data you can update it locally or you can call a function that will fetch data from the API and update your view.
Solution 3:[3]
Dane Mackier - the author of stacked package mentioned this problem, here's the 3 solutions according to him.
Callback from service: Provide a way to set a callback on the service that will be called when anything on the service has been updated and needs a refresh.
Built into the BaseModel: have an internal messaging service that exposes streams for anyone to listen to. When the posts are updated broadcast it over this service. In the model, or the base model, listen for the messages and call notify listeners when anything arrives.
Broadcast all posts again: Expose a stream of posts on the PostsService that the models can subscribe to. When we change anything we broadcast the new posts.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Timur Turbil |
Solution 2 | merfire |
Solution 3 |