简体   繁体   中英

Bloc Pattern: Every screen gets its own bloc?

I am learning the bloc pattern for Flutter and there seems to be a recurring piece of advice that "every screen should have its own bloc".

But what if you queried your server for data that will be used in more than one screen? It seems redundant, and even wasteful, to hit the server several times for the same piece of data, especially if you know that data has not changed (for example, when no operations that mutate/update it have been used).

Is there anyway you can hold that data somehow to reuse it? Is it a good idea to store data used this way at the repository level? Or is this just an accepted cost of using blocs?

Architecture decisions are always highly opinionated and there is no silver bullet.

Well, here you go.


Is there anyway you can hold that data somehow to reuse it?

Offcource yes. You can architect your app like the following way.

Widgets -> Bloc -> Repository -> Local database/ Remote API

So, your bloc will never make any API call directly, but your repo layer will do. Hence, repo layer can decide whether to fetch the data from remote API or local DB or even from the in memory cache. That way, you can reuse the already cached data on multiple screens of your app.

The interesting part is that, unit testing your code will be super easy if you architect your app like this way.


Is it a good idea to store data used this way at the repository level?

Yes.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM