Search code examples
apiflutterdartglobal-variablesfuture

Best practice for fetching data from API periodically and provide it globally (for every Screen)


I'm working on a game-companion app and I was looking for a neat way to fetch data from multiple APIs initiated by starting my app (and maybe also if the user is refreshing the current page with swipe-to-refresh).

The thing is, I planned a dashboard-style homescreen (mostly reduced data from every API), where the user can navigate to different pages (all fed with different API's) and get detailed information for the specific section. I'm not sure how I can provide the API-data 'globally'.

I feel like my main.dart would be way too overloaded, but i can't think of any other way.

What's your thought on that?


Solution

  • Few approaches:

    1. You can use a persistent db and write a wrapper DAO over it that such that anybody with access to this DAO object can write and read from DB. Packages like sqlite help in this regard.

    2. If you are adopting bloc way of state management in your flutter app, then you can create blocs which could be used to share data across your app. flutter_bloc is a good place to start with this.

    3. Via Singleton , If you want a sensitive data that needs to be available within the app globally, then you can create a singleton class that provides read and write from a secure vault. For this secure vault, flutter_secure_storage is convenient or shared_preferences for non sensitive data